Search code examples
mongodb

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


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.


Solution

  • 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.