Skip to content

Instantly share code, notes, and snippets.

@sagarkt
Created April 13, 2020 08:11
Show Gist options
  • Save sagarkt/12849b71c99bfe950508551a2b7da952 to your computer and use it in GitHub Desktop.
Save sagarkt/12849b71c99bfe950508551a2b7da952 to your computer and use it in GitHub Desktop.
Loop Collection and Update documents in MongoDB
var collection = db.getCollection('collectionName');
var bulkOp = collection.initializeOrderedBulkOp();
var count = 0;
collection.find().forEach(function(doc) {
bulkOp.find({ '_id': doc._id }).updateOne({
'$set': { 'email': doc.email.replace('what to replace', 'replace with') }
});
count++;
if(count % 100 === 0) {
// Execute per 100 operations and re-init
bulkOp.execute();
bulkOp = collection.initializeOrderedBulkOp();
}
});
// Clean up queues
if(count > 0) {
bulkOp.execute();
}
// Reference and Credit
// https://stackoverflow.com/a/8588031/1184418
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment