Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

mongodb

As far as I see all commands operate on the same database in mongodb. I want to do something like this:

db.mySourceCollection.find().forEach( function(x){ db.theDestinationCollection.save(x)} );

where mySourceCollection is on liveDatabase and theDestinationCollection is on testDatabase.

like image 671
b7kich Avatar asked Jan 14 '11 03:01

b7kich


People also ask

How do I import data from one database to another in MongoDB?

@Naman what is the use case of copy collection, i mean you need any command or it is ok with manually process? for the manual process just install studio3T connect both databases and right click on collection that you want to copy, click on option "Copy Collection" and then go to second database right click on " ...

How do I insert one document into another in MongoDB?

As we know that in the mongo shell, documents are represented using curly braces ( {} ) and inside these curly braces we have field-value pairs. Now inside these fields, we can embed another document using curly braces {} and this document may contain field-value pairs or another sub-document.

How manually insert data in MongoDB?

The insert() Method To insert data into MongoDB collection, you need to use MongoDB's insert() or save() method.


2 Answers

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

like image 43
Tom Heath Avatar answered Oct 21 '22 00:10

Tom Heath


Use use :-)

> var documents = db.mySourceCollection.find()
> use testDatabase
switched 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!

like image 75
Cameron Avatar answered Oct 20 '22 22:10

Cameron