I am trying to copy a million document in a collection to another colletion.
> db.source_collection.find().forEach(function(doc) { db.dest_collection.insertOne(doc)});
This works fine. but I wonder it might cause any trouble to operating Database if I loop a million documents.
Can I give a sleep while looping in mongh shell?
Is there any better solution for this?
Please advise me.
2
Answers
You can use bulkWrite() rather than insertOne , it will reduce your time significantly.
In this code For every 1000 documents, the code executes the bulk operation using the execute() method, and then re-initializes the bulk operation. Finally, after all documents are processed, the code executes the remaining bulk operation.
If you use the aggregation $out stage, you can copy the documents directly on the server and avoid the network round trip to the client.