Power Guide to MongoDB updateMany Using Mongoose

MongoDB UpdateMany Featured Image

In this tutorial, I will walk you through the MongoDB updateMany method. We shall learn it by using it in a Nodejs project with the help of Mongoose.

The MongoDB updateMany method has become of great use to developers that have chosen MongoDB as the database management system for their software or application.

MongoDB updateMany can come in handy in cases either when you want your users to look up for data that match a given filter and modify all the documents matching that filter.

The syntax for the MongoDB updateMany method is as follows:

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

db.collection.updateMany(
   ,
   ,
   {
     upsert: ,
     writeConcern: ,
     collation: ,
     arrayFilters: [ , ... ],
     hint:  
   }
)

The MongoDB updateMany method was introduced from the version 3.3 release of MongoDB.

How to Use MongoDB updateMany Using Mongoose

Let us take a look at an example where we will build a mini Nodejs application and integrate the Mongoose package into it. This mini-application will help us how we can use MongoDB updateMany in a Nodejs application.

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

Follow the steps below to get started.

  • Navigate to a preferred location in your system and start the terminal. If you’re using Git Bash on Windows, you can simply move to a location. Right-click and select Git Bash here option. Now, you can create your Nodejs project here.
npm init -y
  • Create the entry point file:
touch index.js
  • Now let us open the project in our code editor. We will also install the required packages in our application:
npm i express mongoose
  • Now, let us set up our index.js file by importing the required packages and setting up our 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);
    })
  • Now, set up a port for your app to listen. Make sure this snippet of code lies in the farthest end of the index.js file.
app.listen(3000, () => {
    console.log('Connected to PORT 3000...');
})
  • Next, in your project directory, create a folder named models. We usually do this when we create a full-fledged application. I have done it for a mini app too to conform to the MVC (Models, Views, & Controllers) format. However, you can simply choose to add contents of the file under this folder in index.js file. Although, I will be simply sticking to the MVC format.
  • Now, if you choose to create the models folder, then create a new file named inside the folder named first_model.js., or anything you’d like.
  • Let us import mongoose and create our first 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);
  • Let us suppose our mini shoe store database already comprises of a few documents inside its database:
{ "_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 }
  • Now, let us use the MongoDB updateMany method on these documents and look up using a filter and modify those 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`);
});
  • Now, let us start our MongoDB database server.
  • After that, you must run your Nodejs application to check if the method worked. Instead of running index.js, we will run the product.js model file because that is where our function resides:
node models/product.js

Here’s what our console prints out:

2 items modified

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

Read More: Quick Guide to Export All Collections in MongoDB [2021]

Conclusion

MongoDB updateMany can come in handy in cases either when you want your users to look up for data that match a given filter and modify all the documents matching that filter.

This guide takes you through a quick example where we use the MongoDB updateMany method with the help of Mongoose ODM for MongoDB.

Noteworthy References