December 16, 2016

Example of bulk updates in MongoDB

Mongo Allows to have bulk updates using following operation:

 db.collection.initializeOrderedBulkOp()  

Initializes and returns a new Bulk() operations builder for a collection.

The builder constructs an ordered list of write operations that MongoDB executes in bulk.

Full Example

In this example we will update name from "ABC One" to "ABC Two" in whole collection

 //initialize Bulk operation  
 var bulk = db.test.initializeOrderedBulkOp();   
 db.test.find({"name": /ABC One/})  
   .forEach(function(doc){  
           print (doc.name)      
     name = doc.name.replace("ABC One", "ABC Two")  
           bulk.find({"_id" :doc._id}).  
       updateOne(  
         { $set:   
         {   
           "name": name  
         }}  
       );  
           print(doc.name)                 
   })  
  bulk.execute(); 


No comments:

Post a Comment