This chapter introduces batch operations (bulkWrite) on MongoDB document data using the mongo shell. Here, batch operations not only refer to the batch update of documents mentioned in previous chapters, but also include support for performing a batch of write operations, including document insertion, update, and deletion.

The bulkWrite function is used for batch operations in the mongo shell.

Tip: Batch operations are often used in scenarios requiring batch data synchronization.

Write operations supported by the bulkWrite function

The batch operations support the following combinations of write operations:

  • insertOne - Insert a document
  • updateOne - Update a document
  • updateMany - Update a batch of documents
  • replaceOne - Replace a document
  • deleteOne - Delete a document
  • deleteMany - Delete a batch of documents

Syntax format

db.collection.bulkWrite(
   [ <operation 1>, <operation 2>, ... ],
)

Explanation:

  • operation - Represents the write operation configuration
  • bulkWrite accepts an array of write operations.

Example

Here is a comprehensive example showing the batch execution of a set of document write operations.

db.inventory.bulkWrite(
      [
         // Insert a document
         { insertOne :
            {
            // Document content
               "document" :
               {
                  "_id" : 4, "char" : "Dithras", "class" : "barbarian", "lvl" : 4
               }
            }
         },
         { insertOne :
            {
               "document" :
               {
                  "_id" : 5, "char" : "Taeln", "class" : "fighter", "lvl" : 3
               }
            }
         },
         // Update a document, updateMany is similar for updating a batch of documents
         { updateOne :
            {
               // Update condition
               "filter" : { "char" : "Eldon" },
               // Update content
               "update" : { $set : { "status" : "Critical Injury" } }
            }
         },
         // Delete a document, deleteMany is similar for deleting multiple documents
         { deleteOne :
            // Deletion condition
            { "filter" : { "char" : "Brisbane" } }
         },
         // Replace a document
         { replaceOne :
            {
                // Replacement condition
               "filter" : { "char" : "Meldane" },
               // Replacement content
               "replacement" : { "char" : "Tanys", "class" : "oracle", "lvl" : 4 }
            }
         }
      ]
   );