mongoose bulkWrite

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

Mongoose provides a vast range of methods that can be performed on a MongoDB collection. We may need to use multiple methods at a time on a collection. This can be frustrating. Writing a query and then executing it, again writing another query and then executing it. It goes on like this. So to decrease the effort, we use the mongoose bulkWrite() method that lets us execute multiple methods in one go. In this article, we will discuss how to use the bulkWrite() method in mongoose.

We will use the myteam collection for demonstration.

1
2
3
4
5
{ "_id" : ObjectId("5e30064a80862eae8c9247fd"), "name" : "Leonel Messi", "country" : "Argentina" }
{ "_id" : ObjectId("5e30065980862eae8c9247fe"), "name" : "Cristiano Ronaldo", "country" : "Portugal" }
{ "_id" : ObjectId("5e30068180862eae8c9247ff"), "name" : "Eden Hazard", "country" : "England" }
{ "_id" : ObjectId("5e30069a80862eae8c924800"), "name" : "Marc-Andre ter Stegen", "country" : "Germany" }
{ "_id" : ObjectId("5e3006a980862eae8c924801"), "name" : "Sergio Ramos", "country" : "Spain" }

For performing HTTP endpoint testing, we will use the postman tool. You can download the postman tool from www.getpostman.com.

bulkWrite() in mongoose

In the myteam collection, there are five documents. We will perform the following operations on this collection.

  1. Insert the following document.
1
2
3
4
{
"name" : "Neymar",
"country" : "Brazil"
}
  1. Update the document where the name is “Eden Hazard”. We will change the value of the country field from England to Belgium.

  2. Delete the document where the name is “Sergio Ramos”.

So if we do it without the bulkWrite() method, first, we will use the insert() method, then the updateOne() method, and finally the deleteOne() method. But we have bulkWrite() to do all this in one go. So let’s start by creating a route handler.

1
router.route("/bulkwrite").get(function(req, res) {});

The above route handler will be invoked when the route ‘/bulkwrite’ is executed. Let’s add the bulkWrite() method.

1
2
3
4
5
6
7
8
9
router.route("/bulkwrite").get(function(req, res) {
  myteam.bulkWrite([], function(err, result) {
    if (err) {
      res.send(err);
    } else {
      res.send(result);
    }
  });
});

Currently, we are passing an empty array to the bulkWrite() method. Pay attention here. The bulkWrite() method takes an array of objects as the first argument. In our case, this array will contain three objects, one for insertOne(), one for updateOne() and one for deleteOne(). Let’s create them one by one.

1
2
3
4
5
6
7
{
    insertOne: {
        "document" : {
                "name" : "Neymar",
                "country" : "Brazil"
            }
}}

The document field contains the document that is to be inserted in the collection. Now, let’s create the object for the updateOne() method.

1
2
3
4
5
6
7
8
{   updateOne : {
    "filter" : {"name" : "Eden Hazard"},
        "update" : {
                $set : {
                "country" : "Belgium"
                    }
                }
}}

This is a bit complicated. There are two fields in the updateOne() method – filter and update. The filter will match the document to be updated and the update will contain the change.

The last one is the object for the deleteOne() method.

1
2
3
4
5
6
7
{
    deleteOne : {
        "filter" : {
                "name" : "Sergio Ramos"
                }
            }
}

The deleteOne() method has a single field in it – filter. This is to match the document that is to be deleted. We have to add all these objects in the bulkWrite() method.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
router.route("/bulkwrite").post(function(req, res) {
  myteam.bulkWrite(
    [
      {
        insertOne: {
          document: {
            name: "Neymar",
            country: "Brazil"
          }
        }
      },
      {
        updateOne: {
          filter: { name: "Eden Hazard" },
          update: {
            $set: {
              country: "Belgium"
            }
          }
        }
      },

      {
        deleteOne: {
          filter: {
            name: "Sergio Ramos"
          }
        }
      }
    ],
    function(err, result) {
      if (err) {
        res.send(err);
      } else {
        res.send(result);
      }
    }
  );
});

This looks fine. Let’s execute this using the postman tool and see the results.

Image from Gyazo

The bulkWrite() method returns an object. The value of “ok” is 1. This means the operation was successful. The “writeErrors” and “writeConcernErrors” are empty arrays, meaning no errors. The “insertedIds” field contains the _id of the newly inserted document. The “nInserted”, “nModified”, and “nRemoved”, all these are equal to 1, meaning one document was inserted, one was modified and one was removed. Let’s check through mongo shell.

1
2
3
4
5
6
7
> db.myteam.find()
{ "_id" : ObjectId("5e30064a80862eae8c9247fd"), "name" : "Leonel Messi", "country" : "Argentina" }
{ "_id" : ObjectId("5e30065980862eae8c9247fe"), "name" : "Cristiano Ronaldo", "country" : "Portugal" }
{ "_id" : ObjectId("5e30068180862eae8c9247ff"), "name" : "Eden Hazard", "country" : "Belgium" }
{ "_id" : ObjectId("5e30069a80862eae8c924800"), "name" : "Marc-Andre ter Stegen", "country" : "Germany" }
{ "_id" : ObjectId("5e312ecc252fd940b469085a"), "name" : "Neymar", "country" : "Brazil" }
>

Yes! All the operations were successful.

Conclusion

The bulkWrite() method is indeed a very useful method. It saves effort and reduces the code size. Moreover, it makes the code less complicated. We can execute multiple CRUD operations in just one go.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.