How to do backup or take copy of collection in MongoDB Shell Script?

Priya
Priya
Member
194 Points
47 Posts

I'm trying to do copy a collection to new collection as follows:

db.getCollection('my-orders')
    .forEach(function (myOrders) {
        db.getCollection('my-orders-backup').insertMany([
            myOrders
        ]);
    });

It's working fine for fewer record. But it's taking too much time for more than 20k documents.

Do we have any other way to do backup of a collection?

Views: 108
Total Answered: 1
Total Marked As Answer: 1
Posted On: 14-Dec-2021 04:58

Share:   fb twitter linkedin
Answers
Rahul Maurya
Rahul M...
Teacher
1368 Points
234 Posts
         

Use following aggregate:

db.getCollection('my-orders').aggregate([{ $match: {} }, { $out: "my-orders-backup" }]);

Note: 

  • I can be used within database
  • It will not copy indexes
Posted On: 14-Dec-2021 22:35
Thanks
 - Priya  28-Dec-2021 03:24
 Log In to Chat