MongoDB bulkWrite() Method Examples

Let’s look at some examples of bulkWrite method in MongoDB.

In the following examples, we are working with:

Database: studentsdb

Collection: students

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

Unordered Bulkwrite Example:

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 Example:

If the value of the ordered parameter is set to true, then starting from insertOne, all the operations are executed one by one. BulkWrite will start execution from insertOne, updateOne, updateMany, replaceOne, deleteOne and finally deleteMany. 

The default option for “ordered” is “true”. But if it is set to “false” on a need basis, the results may vary from time to time.

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);
}

MongoDB – bulkWrite() Method

MongoDB is a versatile document-based NoSQL database and can perform DB write operations efficiently using its bulkWrite() method.

The db.collection.bulkWrite() method allows multiple documents to be inserted/updated/deleted at once.

Important Points:

  • db.collection.bulkWrite() 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.

Similar Reads

Syntax

db.collection.bulkWrite([ , , ..., ],{     writeConcern : ,     ordered : })...

MongoDB bulkWrite() Method Operations

Now let us understand the write operations:...

MongoDB bulkWrite() Method Examples

Let’s look at some examples of bulkWrite method in MongoDB....

Conclusion

In this article, we have covered the bulkWrite method in MongoDB. The bulkWrite method is used to perform multiple write operations and control the order of these operations....

Contact Us