Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move a collection from one DB to another DB within the same MongoDB instance

Tags:

mongodb

I have many collections in database A. I want to copy some of them to database B in the same MongoDB.

I tried to copy whole database using db.copyDatabase('A', 'B'), but it has more than 300 GB data. It will take ages to copy and I just want to copy a few collections from database A to database B.

Does anyone know how can I do it?

like image 843
Emily Chen Avatar asked Jan 20 '17 05:01

Emily Chen


People also ask

How do I move a collection 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 create a collection from another collection in MongoDB?

Creating a Collection in MongoDBcreateCollection() is the method used; "name" is a data type - string which is specifying the name of the collection to be formed. "options" is an added document type which helps in specifying the size of memory along with indexing the collection in the database.


2 Answers

You can try it using mongo shell. you can copy collection from one db to another db using renameCollection. the renameCollection can run from admin database so first need to switch to admin db.

so ca follow bellow steps in mongo shell:

step-1: run this comment use admin

step-2: run bellow comment

db.runCommand({renameCollection:"sourcedb.sourceCollection",to:"targetdb.tragetCollection"})

for example:

use admin
db.runCommand({renameCollection:"funnel.countries",to:"test.countries"})

copied countries collection from funnel db to test db.

In background MongoDB will create dump for source collection and restore the dump automatically to target db collection

like image 92
Shaishab Roy Avatar answered Sep 29 '22 19:09

Shaishab Roy


Use mongodump to dump the collections:

mongodump  --db A --collection coll --out yourbackupdir

and then import the collections using mongorestore:

mongorestore --db B --collection coll yourbackupdir/
like image 45
ares Avatar answered Sep 29 '22 18:09

ares