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?
@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 " ...
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.
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
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With