Skip to content
Related Articles

Related Articles

MongoDB – db.collection.bulkWrite() Method

View Discussion
Improve Article
Save Article
  • Last Updated : 21 Jul, 2021
View Discussion
Improve Article
Save Article

MongoDB is a versatile documentum based NoSQL database and has the ability to perform DB write operations efficiently by means of its bulkWrite() method. That means multiple documents can be inserted/updated/deleted in one shot.

  • This method can be used in multi-document transactions.
  • If this method encounters an error in the transaction, then it will throw a BulkWriteException.
  • By default, this method executes operations in order.

Syntax :

db.collection.bulkWrite(

[ <opr1>, <opr2>, …,<oprn> ],

{

     writeConcern : <your document and this is optional>,

     ordered : <true/false, defaults to true and this is optional>

}

)

Parameters:

  • [ <opr1>, <opr2>, …,<oprn> ]: It is an array of write operations, i.e., insertOne, updateOne, updateMany, deleteOne, deleteMany, replaceOne.
  • writeConcern: It is a document that expresses write concern. If you want to use the default write concern then remove this parameter, It is an optional parameter.
  • ordered: As multiple operations can be performed, when ordered (default to true) is not provided, all the operations are proceeded one by one and if given as ordered : false, results of the operation differs as sometimes insertOne will be the first followed by the rest and sometimes deleteOne is followed first and if it is the case, without any document existence, it cannot be completed. Hence providing “ordered” parameter to false should be taken into consideration whether required or not

Return:

This method will return a document that contains a boolean acknowledged as true (if the write concern is enabled) or false (if the write concern is disabled), count for every write operation and an array that contains an _id for each and every successfully inserted or upserted documents.

Write Operations:

Now let us understand the write operations:

In the following write operations, we are working with:

Database: studentsdb

Collection: students

Document: three documents that contain the details of the students.

1. insertOne Operation:

insertOne is used to insert one document in the collection.

Syntax:

db.collection.bulkWrite([{insertOne: {“document” : <document>}}])

Example:

Let us apply insertion of 2 documents and check the output of it:

try{

… db.students.bulkWrite([

… {insertOne:{“document”:{studentId:4, studentName:”GeekD”, studentAge:24}}},

… {insertOne:{“document”:{studentId:4, studentName:”GeekD”, studentAge:24}}}

… ]);

… }catch(e){

… print(e);

… }

As the above query contains two “insertOne” statements, 2 documents got inserted properly. Here, “insertedids’ represent the values that got inserted. Now, n execution of find(), we can see the new documents are inserted perfectly

“_id” column is the unique one to identify the document. In our example, for _id, randomly the value is picked. We can explicitly set the value of _id to 1, 2 etc., _id column behaves like Primary key concept so, we are not allowed to insert duplicate rows.

2. updateOne and updateMany Operation:

updateOne is used to update one document in the collection.

Syntax:

db.collection.bulkWrite([{updateOne

{“filter”: <document>,

“update”:<document>,

“upsert”:<boolean>,

“collation”:<document>,

“arrayFilters”:[<filterdocument1>, <filterdocument2>,..]

“hint”:<document|string>

}

}])

Example:

We need to provide valid filter condition i.e. need to check the columns correctly (mongodb case-sensitive) and provide the columns to be updated.

try {
  db.students.bulkWrite([
     { updateOne : {
        "filter" : { "studentId" : 2 }, 
        "update" : { $set : { "studentName" : "GeekyBest" } }
     } }
  ]);
} catch (e) {
  print(e);
} 

Here, first “filtered” for “studentId = 2” and if present, updated the “studentName” to “GeekyBest” by using “updateOne”. If multiple documents match for the given filtration, then “updateOne”, updates first document the matches the given condition in the collection. Hence, in the above process, for one document, the update is done. “studentId” and “studentid” are treated differently because mongodb is case sensitive.

updateMany is used to update all the documents that match the given condition in the collection.

Syntax:

db.collection.bulkWrite([{updateMany

{“filter”: <document>,

“update”:<document>,

“upsert”:<boolean>,

“collation”:<document>,

“arrayFilters”:[<filterdocument1>, <filterdocument2>,..]

“hint”:<document|string>

}

}])

Example:

try {
  db.students.bulkWrite([
     { updateMany : {
        "filter" : { "studentId" : 4 },
        "update" : { $set : { "studentName" : "GeeksForGeeksbest" } }
     } }
  ]);
} catch (e) {
  print(e);
}   

“matchedCount” represents how many documents got matched and it shows 1 because 1 document matched for the filtered condition and hence the matched document “studentName” got changed.

3. replaceOne Operation:

replaceOne replaces a single document according to the match that is provided in the filter. Even when multiple documents are matched, replaceOne will always replace the first matched document.

Syntax:

db.collection.bulkWrite([{replaceOne : 

{“filter”: <document>,

“replacement”:<document>,

“upsert”:<boolean>,

“collation”:<document>,

“hint”:<document|string>

}

}])

Example:

try {
  db.students.bulkWrite([
     { replaceOne : {
        "filter" : { "studentId" : 3 },
        "replacement" : { "studentId" : 30, "studentName" : "BestGeek" }
     } }    
  ]);
} catch (e) {
  print(e);
}

In the above example, we checked for “studentId = 3” and one document is matched the given filter and the following replacements are done i.e. “studentId = 30 and studentName = BestGeek” are the replacements done and they are replaced also.

4. deleteOne and deletMany Operation:

deleteOne deletes a single document according to the match that is provided in the filter. Even when multiple documents are matched, deleteOne will delete the first matching document only always.

Syntax:

db.collection.bulkWrite([{deleteOne : 

{“filter”: <document>,

“collation”:<document>

}

}])

Example:

try {
  db.students.bulkWrite([
     { deleteOne : { "filter" : { "studentId" : 30} } }  
  ]);
} catch (e) {
  print(e);
}

Here, “deleteone” will delete a document that match the given filter(i.e,”studentId” : 30)

deleteMany will delete all the documents that are matching. Hence, it depends upon the requirement, we need to see whether we can go for deleteMany or not. In the production kind of environment, deletion is of high cost, we cannot revoke it and hence should be very careful in doing that.

Syntax:

db.collection.bulkWrite([{deleteMany : 

{“filter”: <document>,

“collation”:<document>

}

}])

Example:

try {
  db.students.bulkWrite([
     { deleteMany : { "filter" : { "studentAge" : 20} } }  
  ]);
} catch (e) {
  print(e);
}

 Here, “deleteMany” will delete those documents that match the given filter(i.e,”studentAge” : 20)

Examples:

In the following examples, we are working with:

Database: studentsdb

Collection: students

Document: four documents that contain the details of the students.

Unordered Bulkwrite:

Here, the bulkWrite method executes multiple unordered operations because the value of the ordered parameter is set to false.

try {
  db.students.bulkWrite([
     {insertOne:{"document":{studentId:5, studentName:"GeekE", studentAge:24}}},
     { updateOne : {
        "filter" : { "studentId" : 2 }, 
        "update" : { $set : { "studentName" : "GeekyBest" } }
     } },
     { deleteMany : { "filter" : { "studentAge" : 20} } }, 
     { replaceOne : {
        "filter" : { "studentId" : 3 },
        "replacement" : { "studentId" : 30, "studentName" : "BestGeek" }
     } }  
  ],{ ordered : false });
} catch (e) {
  print(e);
}

Ordered BulkWrite:

If the value of the ordered parameter is set to true, then starting from insertOne, all the operations are executed one by one. That is BulkWrite will start executing from insertOne, updateOne, updateMany, replaceOne, deleteOne and finally deleteMany. The default option for “ordered” is “true”. But if it is set to “false” on need basis, the results may vary from time to time. i.e order of execution cannot be defined and hence sometimes deleteOne/deleteMany will be worked out and then insertOne/updateOne or the rest will occur.

try {
  db.students.bulkWrite([
     {insertOne:{"document":{studentId:5, studentName:"GeekE", studentAge:24}}},
     { updateOne : {
        "filter" : { "studentId" : 2 }, 
        "update" : { $set : { "studentName" : "GeekyBest" } }
     } },
     { deleteMany : { "filter" : { "studentAge" : 20} } }, 
     { replaceOne : {
        "filter" : { "studentId" : 3 },
        "replacement" : { "studentId" : 40, "studentName" : "Geek11" }
     } }  
  ],{ ordered : true });
} catch (e) {
  print(e);
}


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!