I have got mongo db called test
and in this db two collections collection1
and collection1_backup
. How to replace content of collection1
with data from collection1_backup
.
MongoDB – copyTo() Method In MongoDB, copyTo() method is used to copies all the documents from one collection(Source collection) to another collection(Target collection) using server-side JavaScript and if that other collection(Target collection) is not present then MongoDB creates a new collection with that name.
@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 " ...
Paste MongoDB collection Select your target MongoDB database (or collection) that you want to copy your source collection to. In our example, that is database “test” on server “ADX”. Right-click your target and choose Paste Collection.
The best way to have done this (considering the name of the collection ends with _backup
) is possibly to have used mongorestore: http://docs.mongodb.org/manual/reference/mongorestore/
However in this case it depends. If the collection is unsharded you can use renameCollection
( http://docs.mongodb.org/manual/reference/command/renameCollection/ ) or you can use a more manual method of (in JavaScript code):
db.collection1.drop(); // Drop entire other collection db.collection1_backup.find().forEach(function(doc){ db.collection1.insert(doc); // start to replace });
Those are the most common methods of doing this.
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