Exploring bulkWrite

Exploring bulkWrite

Table of contents

No heading

No headings in the article.

MongoDB has many interesting built-in methods, and one of them is bulkWrite, which allows batch processing of write operations in a specified order. This method has been available since version 3.2.

The syntax of bulkWrite is simple:

db.collection.bulkWrite( 
[ <operation 1>, <operation 2>, ... ], 
{ writeConcern: , 
ordered: } )

Let's explain the parameters mentioned above:

  • operation 1, operation 2: These represent the write operation objects. For example, an insert operation can be defined as follows:
{ 
 insertOne: { 
    document: { _id: 3, type: "spider", size: "medium", price: 6 } 
 } 
}
  • writeConcern: It represents the write settings that determine when a write operation is considered successful, especially in a multi-node MongoDB setup. Starting from version 5.0, the default setting is {w: 'majority'}, which means that the write operation is considered successful when the majority of nodes have finished writing. For example, if there are three nodes, the write operation is considered successful if two or more nodes have successfully written the data.

  • ordered: When this parameter is set to true, the write operations are strictly executed in sequential order. This means that operation 1 is executed first, followed by operation 2. If any operation encounters an error during this process, MongoDB returns the result and does not execute the remaining write operations.

    When ordered is set to false, the write operations can be executed concurrently without a specific order. If any write operation encounters an error, MongoDB continues to execute the remaining operations and returns the errors and exceptions at the end.

It can be observed that the ordered mode of bulkWrite is slower compared to the unordered mode.