8

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?

2 Answers 2

13

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

Sign up to request clarification or add additional context in comments.

6 Comments

It is working perfectly! Thank you so much . I thought renameCollection only works when you want to change the collection name!
Also, I wonder will it work if i put different collections in one query, or I only can move one collection at each time. I am going to try
This will move the collection, not a copy (as it is a rename)
It is a dump and restore. I just renamed a 3GB collection to another DB. It took a few minutes.
Note: collection indices are not preserved with this operation! You may want to re-create them.
|
4

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/

2 Comments

Thanks for answering. But in my case , I just want to move few collections because it is too much to dump whole database.
There is no need to store it to a file. Use STDOUT and STDIN: mongodump --db=A --collection=coll --archive=- | mongorestore --nsFrom="A.coll " --nsTo="B.coll " --archive=- Collections can be specified by wild-card characters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.