Update Multiple Documents using updateMany() in MongoDB

A MongoDB database has multiple collections. These collections can store millions of documents(data in MongoDB is called a document). Sometimes it is required to update these documents.

MongoDB has various methods to update the documents of a collection such as update(), updateMany(), findOneAndUpdate(), findAndModify(), etc. We already have covered the update(), findOneAndUpdate() and findAndModify() methods in separate tutorials.

In this tutorial, we will provide a comprehensive guide to using MongoDB’s updateMany() method to update the documents.

MongoDB updateMany() Method

The MongoDB UpdateMany() method has become very useful for developers who have chosen MongoDB as the database for their applications. This is useful when you want to modify all documents that match a given filter. It has the power to update multiple documents at once, making it fast and highly useful when developing real-time applications.

Syntax:

Below is the syntax of using updateMany() method in MongoDB.

db.collection.updateMany(filter, update, options)

or

db.collection.updateMany(
   filter,
   update,
   {
     upsert: boolean,
     writeConcern: document,
     collation: document,
     arrayFilters: [ filterdocument1, ... ],
     hint:  document|string
   }
)

The MongoDB updateMany() method was introduced in the version 3.3 release.

Example of using the MongoDB updateMany() method in Node.js

Let us take a look at an example of building an application that will help us how we can use MongoDB updateMany() in Node.js.

You can take the help of this example to change multiple documents in the database with a single command.

Below is the step-by-step guide to creating a demo project using Node.js, Express.js, MongoDB and Mongoose to demonstrate the example:

Project Setup

  • Create a project folder and locate it on a terminal.
  • Execute the below command to initiate NPM:
npm init -y

Once you pass this command, you should see a package.json file created in your project directory.

  • Create the entry point file:
touch index.js
  • Install the required NPM packages for our project:
npm i express mongoose

Importing modules and making connections to the database

  • Inside the “index.js” file, import all of the packages we installed then set up the MongoDB database connection:
const express = require('express');
const app = express();
const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/mySampleDB', { useNewUrlParser: true, useUnifiedTopology: true })
    .then(() => {
        console.log(`CONNECTED TO MONGO!`);
    })
    .catch((err) => {
        console.log(`OH NO! MONGO CONNECTION ERROR!`);
        console.log(err);
    })
  • Next, at the end of the app.js file, it is required to set up a localhost port for the app server to listen:
app.listen(3000, () => {
    console.log('Connected to PORT 3000...');
})

Creating Models

  • Next, in your project directory, create a folder named models. We usually do this when we create a full-fledged application to conform to the MVC (Models, Views, & Controllers) format.
  • Create a new file inside the folder named product.js.
  • Next, import mongoose and create a schema and model in this file. Let’s say we are managing a mini-shoe store database.
const mongoose = require('mongoose');
const shoeSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    price: {
        type: Number,
        required: true,
        min: 0
    },
    sizeUK: {
        type: Number,
        required: true,
        min: 5
    },
    onSale: {
        type: Boolean,
        default: false
    }
})

const Shoe = mongoose.model('Shoe', productSchema);
  • To demonstrate the use of the updateMany() method, we have inserted the following document inside the model we have created.
{ "_id" : 1000, "name" : "Nike Air Force 1", "price" : 4,999, "sizeUK" : 6, "onSale" : false }
{ "_id" : 1001, "name" : "X Speedflow.4 Flexible Ground Boots", "price" : 5,999, "sizeUK" : 7, "onSale" : true }
{ "_id" : 1002, "name" : "Men's Reebok Running Ztaur Run Shoes", "price" : 9,999, "sizeUK" : 8, "onSale" : true }
{ "_id" : 1003, "name" : "Puma RS - Z Art of Sport Unisex Sneakers", "price" : 8,999, "sizeUK" : 8, "onSale" : true }

Using updateMany() method

  • Now, let’s demonstrate the use of the MongoDB updateMany() method on these documents.
const myFilterQuery = { sizeUK: 8 };
const changeValuesTo = { $set: { "onSale": false } };

Shoe.updateMany(myFilterQuery, changeValuesTo, function (err, res) {
    if (err) throw error;
    console.log(`${res.result.nModified} items modified`);
});

Here we have passed a query to select the documents having a key “sizeUK” equal to 8 and passed another argument to change the “onSale” key of all the matched documents to false.

Then inside the callback, we check for the error and print the number of documents modified by this method.

Run the Application:

  • To run the application, make sure that the MongoDB server is up and running in the background.
  • After that, instead of running index.js, we will run the product.js model file because that is where our method resides:
node models/product.js

Output:

Here’s what our console prints out:

2 items modified

This way we have successfully made use of the MongoDB updateMany() method using Mongoose.

Conclusion

The best way to update multiple MongoDB documents on a given filter is with updateMany(). The updateMany() method has the ability to update multiple documents at once. In this tutorial, we have learned to use updateMany() method in Node.js and demonstrated an example to update multiple documents using it.

References

https://www.mongodb.com/docs/manual/reference/method/db.collection.updateMany/#syntax

https://stackoverflow.com/questions/1740023/mongodb-how-to-update-multiple-documents-with-a-single-command

Aneesha S
Aneesha S
Articles: 172