How do I insert a record from one mongo database into another? How do I insert a record from one mongo database into another? mongodb mongodb

How do I insert a record from one mongo database into another?


Use use :-)

> var documents = db.mySourceCollection.find()> use testDatabaseswitched to db testDatabase> documents.forEach(function(x){ db.theDestinationCollection.insert(x) })

db is used to refer to the currently connected database, however you can switch databases on the fly using the use command, as I've shown above.

Check out the help command in the shell -- it mentions this command and much more!


use dbname doesn't work in scripted mode (i.e. when scripting the shell with javascript), so you should use the db.getSiblingDB() method instead to reassign the 'db' variable, e.g.:

db = db.getSiblingDB("otherdb")

More info here: http://www.mongodb.org/display/DOCS/Scripting+the+shell