Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongo copy from one collection to another (on the same db)

Tags:

mongodb

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.

like image 736
Marcin Wasiluk Avatar asked Dec 17 '12 14:12

Marcin Wasiluk


People also ask

How do you copy a collection in MongoDB of the same database?

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.

How do I copy a collection from one MongoDB to another?

@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 copy a collection in MongoDB Atlas?

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.


1 Answers

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.

like image 97
Sammaye Avatar answered Sep 28 '22 08:09

Sammaye