Emily Chen
Emily Chen

Reputation: 123

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

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?

Upvotes: 8

Views: 12054

Answers (2)

Shaishab Roy
Shaishab Roy

Reputation: 16805

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

Upvotes: 13

ares
ares

Reputation: 4413

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/

Upvotes: 4

Related Questions