MongoDB Bulk Write Operations

Posted By : Mohit Jain | 28-Oct-2018

In Mongo DB we can perform bulk write operations like:-

1.)Bulk.insert()

2.)Bulk.find.remove()

3.)Bulk.find.replaceOne()

4.)Bulk.find.updateOne

5.)Bulk.find.update() etc.

 

Here are the things we require to perform bulk operations:-

 

1.)  Bulk():- This is a bulk operation builder which is used to create list of write operations for a single collection.We have to initialize this builder in order to add the write operation list   by using below points either by 2.) or 3.) 

 

2.)db.collection.initializeOrderedBulkOp():- This is used to initialize Bulk() so that all write operations will execute sequentially.But this case has one limitation that if any of the error occurs while executing any operation in the list then remaining list operations will not execute further. 

 

3.)db.collection.initializeUnorderedBulkOp():-This is used to initialize Bulk() so that all write operations will execute in unsequentially or in any order.The advantage of this over 2.) is that if any error occurs whiile executing any write operations then it will not effect remaining operations in the list.

 

4.)Bulk.execute():-This method is used to finally responsible to excute whole list of write operations. 

Example:-

First initialize lets say we have collection with name items

var bulkOperationList = db.items.initializeUnorderedBulkOp();

 Then add write operations in the list 

//add insert operations

bulkOperationList.insert( { item: "abc", defaultQty: 10, status: "B", points: 100 } );
bulkOperationList.insert( { item: "ijk", defaultQty: 200, status: "B", points: 200 } )
bulkOperationList.insert( { item: "mop", defaultQty: 0, status: "P", points: 0 } );

//add update operations

bulkOperationList.find( { status: "B" } ).updateOne( { $set: { status: "I", points: "0" } } );
bulkOperationList.find( { status: "B" } ).update( { $set: { status: "I", points: "0" } } );

//add remove operations

bulkOperationList.find( { status: "D" } ).remove();
bulkOperationList.find( { status: "D" } ).removeOne();

//add replace operation

bulkOperationList.find( { item: "abc123" } ).replaceOne( { item: "abc123", status: "P", points: 100 } );
 
etc.
Now finally execute whole list of above operations.
bulkOperationList.execute();

 

Request for Proposal

Name is required

Comment is required

Sending message..