How to use Mongoose to Update in Bulk

Introduction

Of all the four CRUD operations, the update is the one that needs to be done very carefully, especially when there are bulk of documents to be updated. One single mistake can lead to serious trouble. Imagine, there are hundreds of documents in a collection and we try to update the bulk of documents in one go, say seventy documents. Now, if there is a small mistake in the query, we will end up updating those documents too which does not need any modifications. Then, going back to the old data will be impossible and we will need to start everything again. So whenever we are performing update operations in bulk, we need to do it carefully. In this article, we will discuss how to use Mongoose to Update in Bulk and taking caution to ensure the updates are safely executed.

We will perform the update operation on the details collection.

{ "_id" : ObjectId("5dc68b527845ea474092d008"), "name" : "John", "age" : 21, "location" : "New York" }
{ "_id" : ObjectId("5dc68b5e7845ea474092d009"), "name" : "Sam", "age" : 24, "location" : "Chicago" }
{ "_id" : ObjectId("5dc68b717845ea474092d00a"), "name" : "Mike", "age" : 29, "location" : "New York" }
{ "_id" : ObjectId("5dc68b8b7845ea474092d00b"), "name" : "Lisa", "age" : 27, "location" : "New York" }
{ "_id" : ObjectId("5dc68b9a7845ea474092d00c"), "name" : "Ray", "age" : 31, "location" : "Chicago" }
{ "_id" : ObjectId("5dc68ba77845ea474092d00d"), "name" : "Sunny", "age" : 36, "location" : "Detroit" }
{ "_id" : ObjectId("5dc68bb77845ea474092d00e"), "name" : "Ronn", "age" : 26, "location" : "New York" }
{ "_id" : ObjectId("5dc68bc87845ea474092d00f"), "name" : "Sophie", "age" : 34, "location" : "New York" }
{ "_id" : ObjectId("5dc68bd47845ea474092d010"), "name" : "Kane", "age" : 39, "location" : "New York" }
{ "_id" : ObjectId("5dc68be67845ea474092d011"), "name" : "Emma", "age" : 29, "location" : "Detroit" }

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

Mongoose updateMany() method

Out of various methods provided by mongoose, the updateMany() method is used to update documents in bulk. So let’s discuss how we can use the updateMany() method in mongoose.

The following route handler will be executed when the endpoint ‘/updateInBulk’ will be invoked.

router.route("/updateInBulk").put(function(req, res) {});

Let’s insert the updateMany() method in it.

details.updateMany({}, {}, function(err, result) {
  if (err) {
    res.send(err);
  } else {
    res.send(result);
  }
});

The updateMany() method has three mandatory parameters – the query, the update and a callback function. The callback function, in turn, has two parameters – an error (if any occurs) and the result.

Currently, we passed an empty object as the first and second parameters. We need to provide a condition and according to this condition, the documents will be updated. In the details collection, there are multiple documents where the value of the location field is “New York”. Let’s update the location to “Texas”, where the value of the location field is “New York”.

Be careful while defining the query. The condition in it will match the documents. If anything goes wrong here, even a bit, the collection will get all messed up. So, we want to match the documents where the location is “New York”.

{"location" : "New York"}

The query looks fine. Now, pay attention to the update part. We can use the $set operator here.

{ $set : { "location" : "Texas"}}

Or this can also work.

{"location" : "Texas"}

Let’s add these objects in the updateMany() method.

router.route("/updateInBulk").put(function(req, res) {
  details.updateMany(
    { location: "New York" },
    { $set: { location: "Texas" } },
    function(err, result) {
      if (err) {
        res.send(err);
      } else {
        res.send(result);
      }
    }
  );
});

Let’s execute this route using the postman tool and see what happens.

Image from Gyazo

The updateMany() method returns an object.

  1. n – number of documents matched the query
  2. nModified – number of documents modified
  3. ok – 1 if the operation was successful

The value of the nModified is 6. This means six documents were updated. Let’s verify using the mongo shell.

> db.details.find()
{ "_id" : ObjectId("5dc68b527845ea474092d008"), "name" : "John", "age" : 21, "location" : "Texas" }
{ "_id" : ObjectId("5dc68b5e7845ea474092d009"), "name" : "Sam", "age" : 24, "location" : "Chicago" }
{ "_id" : ObjectId("5dc68b717845ea474092d00a"), "name" : "Mike", "age" : 29, "location" : "Texas" }
{ "_id" : ObjectId("5dc68b8b7845ea474092d00b"), "name" : "Lisa", "age" : 27, "location" : "Texas" }
{ "_id" : ObjectId("5dc68b9a7845ea474092d00c"), "name" : "Ray", "age" : 31, "location" : "Chicago" }
{ "_id" : ObjectId("5dc68ba77845ea474092d00d"), "name" : "Sunny", "age" : 36, "location" : "Detroit" }
{ "_id" : ObjectId("5dc68bb77845ea474092d00e"), "name" : "Ronn", "age" : 26, "location" : "Texas" }
{ "_id" : ObjectId("5dc68bc87845ea474092d00f"), "name" : "Sophie", "age" : 34, "location" : "Texas" }
{ "_id" : ObjectId("5dc68bd47845ea474092d010"), "name" : "Kane", "age" : 39, "location" : "Texas" }
{ "_id" : ObjectId("5dc68be67845ea474092d011"), "name" : "Emma", "age" : 29, "location" : "Detroit" }
>

Yes! All the documents where the location was New York are updated.

Conclusion

We have discussed how to update documents in bulk using Mongoose and the updateMany method. We hope this instructional tutorial has been useful to you and helps you in your application. If you need database help please don’t hesitate to contact us at Object Rocket.

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.