bulkWrite() in MongoDB – Detailed 2023 Guide

MongoDB is a well-known record-situated data set administration framework that permits designers to store mammoth measures of information. It is open-source and exceptionally effective. In spite of the fact that it can in some cases get very perplexing for amateurs when learning without an ODM, it has exact documentation. It is a NoSQL-type information base that stores information in BSON design as reports inside assortments.

Top-level like Facebook, Google, Adobe, Nokia, and numerous others have picked MongoDB to store their enormous measures of information.

MongoDB offers an assortment of operators, capacities, and techniques that can be utilized for various purposes. It has given designers straightforward just as adaptable administrators that permit them to do significantly more than CRUD in a MongoDB-upheld application. This is likewise one justification for why MongoDB is so well known.

With the assistance of operators and functions in MongoDB, you redo questioning, printing, and editing. It has discovered being a fan even among novices alongside senior developers.

MongoDB bulkWrite() Method

The bulkWrite() method in MongoDB is used to perform bulk writing operations in an order of execution with controls. You can also choose to go for an unordered bulk write by setting the option ordered false.

Don’t get confused by the above definition, we will provide several examples to understand it better, but first, let’s take a look at the syntax.

Syntax:

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

bulkWrite() in MongoDB accepts an array of operations to it.

The bulkWrite() operation can only be used with a specific number of write operations:

  • insertOne
  • updateOne
  • updateMany
  • deleteOne
  • deleteMany
  • replaceOne

Let us proceed with the examples of different operations in bulkWrite() in MongoDB.

Using bulkWrite() with insertOne

We have some documents in a collection ‘shoes’ that we will use to demonstrate the use of bulkWrite() method with different operations.

> db.shoes.find({}).pretty()
{
        "_id" : ObjectId("616714c6461c6d31d88b4d90"),
        "name" : "Dmitri Vu's Highs",
        "price" : 5300,
        "size" : 8,
        "style" : "Chelsea Boots",
        "__v" : 0,
        "onSale" : false,
        "freeDelivery" : false
}
{
        "_id" : ObjectId("616714c6461c6d31d88b4d91"),
        "name" : "Purple Haven Lavender Kittens",
        "price" : 14610,
        "size" : 9,
        "style" : "Kitten Heels",
        "onSale" : false,
        "freeDelivery" : false
}
{
        "_id" : ObjectId("616714c6461c6d31d88b4d92"),
        "name" : "Marlo Wood’s Lite Moccasins",
        "price" : 8880,
        "size" : 9,
        "style" : "Moccasins",
        "onSale" : false,
        "freeDelivery" : false
}
{
        "_id" : ObjectId("616714c6461c6d31d88b4d93"),
        "name" : "Myrna's D'Orsays",
        "price" : 9760,
        "size" : 7,
        "style" : "D'Orsay",
        "__v" : 0,
        "onSale" : false,
        "freeDelivery" : false
}
{
        "_id" : ObjectId("616716ad33e9f410d4cdfded"),
        "name" : "Choco-Lita YMX 60",
        "price" : 3400,
        "size" : 9,
        "style" : "Lita",
        "__v" : 0,
        "onSale" : false,
        "freeDelivery" : false
}
{
        "_id" : ObjectId("61671f63e97d0a62702d57b5"),
        "name" : "Starvis Thigh Highs Mango Yellow",
        "price" : 10580,
        "size" : 8,
        "style" : "Thigh High Boots",
        "onSale" : false,
        "freeDelivery" : false
}
{
        "_id" : ObjectId("61685f0884b1142f7b3ec59d"),
        "name" : "Pink Belly Shoes",
        "price" : 2580,
        "size" : 7,
        "style" : "Belly Shoes",
        "onSale" : true,
        "freeDelivery" : true
}
{
        "_id" : ObjectId("6169b42739fcb911f638b069"),
        "name" : "Athena Silver Kitten Heels",
        "price" : 13380,
        "size" : 6,
        "style" : "Kitten Heels",
        "onSale" : true,
        "freeDelivery" : true
}
{
        "_id" : ObjectId("6169b42739fcb911f638b06a"),
        "name" : "Brenda’s Desert Wedges",
        "price" : 18580,
        "size" : 8,
        "style" : "Wedges",
        "onSale" : false,
        "freeDelivery" : true
}

Use the bulkWrite() method along with the insertOne operation to insert a document into the above collection.

insertOne is used to insert a document into a collection, we have a separate tutorial on inserting documents in a MongoDB collection, if you want to read click here.

> db.shoes.bulkWrite([ { insertOne: { document: { "name" : "Golden Shimmery Pumps",
...         "price" : 17930,
...         "size" : 7,
...         "style" : "Pumps",
...         "onSale" : true,
...         "freeDelivery" : false
... } } }])


{
        "acknowledged" : true,
        "deletedCount" : 0,
        "insertedCount" : 1,
        "matchedCount" : 0,
        "upsertedCount" : 0,
        "insertedIds" : {
                "0" : ObjectId("6169c15039fcb911f638b06b")
        },
        "upsertedIds" : {

        }
}

Here in the return object, we see that the “insertedCount” is 1, which means one document is inserted.

Using bulkWrite() with updateOne

The updateOne filter with bulkWrite() in MongoDB will only update the first matching document in the filter. Let’s see a demonstration.

> db.shoes.bulkWrite([
... {
...      updateOne:
...            {
...                 "filter": { "name" : "Marlo Wood’s Lite Moccasins" },
...                 "update" : { $set : { "name" : "Marlo Wood’s Teal Moccasins" } }
...             }
... }
... ])


{
        "acknowledged" : true,
        "deletedCount" : 0,
        "insertedCount" : 0,
        "matchedCount" : 1,
        "upsertedCount" : 0,
        "insertedIds" : {

        },
        "upsertedIds" : {

        }
}

Using bulkWrite() with deleteOne

The deleteOne operation is used with bulkWrite() in MongoDB to delete a document.

> db.shoes.bulkWrite([
... { deleteOne :
...             { "filter" : { "name" : "Myrna's D'Orsays" } }
...          },
... ])


{
        "acknowledged" : true,
        "deletedCount" : 1,
        "insertedCount" : 0,
        "matchedCount" : 0,
        "upsertedCount" : 0,
        "insertedIds" : {

        },
        "upsertedIds" : {

        }
}

Here in the return object, we see that the “deletedCount” is 1, which means one document is deleted.

We covered deleteOne in another tutorial: NodeJS MongoDB Remove.

Using bulkWrite() with replaceOne

The replaceOne operation with bulkWrite() is used in MongoDB to replace a value of a document.

> db.shoes.bulkWrite([
...          { replaceOne :
...             {
...                "filter" : { "name" : "Brenda’s Desert Wedges" },
...                "replacement" : { "name" : "Brenda’s Desert Wedges (Limited Edition)", "onSale" : true, "price" : 13900 }
...             }
...          }
...  ])


{
        "acknowledged" : true,
        "deletedCount" : 0,
        "insertedCount" : 0,
        "matchedCount" : 1,
        "upsertedCount" : 0,
        "insertedIds" : {

        },
        "upsertedIds" : {

        }
}

Want to know more about replaceOne filter? Click here to read our guide to it

Performing Bulk Writing using the bulkWrite() Method with multiple operations

The bulkWrite() method can be able to perform different operations at once. Let’s try to get it.

> db.shoes.bulkWrite(
...       [
...          { insertOne :
...             {
...                "document" :
...                {
...                   "name" : "Miranda Bane’s Ankle Boots", "size" : 6, "style" : "Ankle Boots", "price" : 30000, "onSale" : true, "freeDelivery" : false
...                }
...             }
...          },
...          { updateOne :
...             {
...                "filter" : { "name" : "Starvis Thigh Highs Mango Yellow" },
...                "update" : { $set : { "price" : 12350 } }
...             }
...          },
...          { deleteOne :
...             { "filter" : { "name" : "Purple Haven Lavender Kittens" } }
...          },
...          { replaceOne :
...             {
...                "filter" : { "name" : "Choco-Lita YMX 60" },
...                "replacement" : { "freeDelivery" : true, "onSale" : true, "price" : 5500 }
...             }
...          }
...       ]
...    )



{
        "acknowledged" : true,
        "deletedCount" : 1,
        "insertedCount" : 1,
        "matchedCount" : 2,
        "upsertedCount" : 0,
        "insertedIds" : {
                "0" : ObjectId("6169dad339fcb911f638b06c")
        },
        "upsertedIds" : {

        }
}

Here in the above output, we can see that bulkWrite() successfully completes all the specified operations without any error, which means it can able to do multiple operations at once, which is one of the reasons for its popularity.

Conclusion

The bulkWrite() is a great way to perform write operations on a document with control of the order of execution. The bulkWrite() is also preferred to be used when multiple operations need to be performed at once. In this tutorial we have provided you with demonstrations of various operations, hope you find this tutorial helpful.

Reference

https://www.mongodb.com/docs/manual/reference/method/db.collection.bulkWrite/

Aneesha S
Aneesha S
Articles: 172