In our previous tutorial, we learned everything about MongoDB findOneAndUpdate() and findAndModify() methods, but these methods can only update one document at a time and can be suitable for cases like updating a particular post, updating a single user information, etc.
In cases where we have to update multiple documents based on some conditions, like where the age field is greater than 18 or something, these methods are not applicable, instead, we have to use updateMany(). Let’s learn about it in detail.
MongoDB updateMany() Method
The MongoDB updateMany() method updates documents in a collection that matches the given condition. Even if multiple documents satisfy the filter condition, it selects all of them for the update operation unlike findOneAndUpdate(), findAndModify() and updateOne() which only update the first one.
updateMany() was introduced with the release of MongoDB 3.2 in December 2015. The ability to update multiple documents simultaneously makes this method highly useful when developing real-time applications.
Syntax:
db.collection.updateMany(
filter,
update,
options
)
Parameters:
- filter: Query or condition to select documents.
- update: Update operation to apply.
- options: Optional parameters like upsert, writeConcern, collation, arrayFilters and hint.
Return:
It returns an object containing different information about the operation like the number of documents that matched the filter (matchedCount), the number of documents modified (modifiedCount), etc.
Using updateMany() in Node.js
In this section, we will see how to use updateMany() in Node.js. We will start off by creating a simple Node.js application and then try to update multiple documents with a single command using this method.
Follow the steps below to learn how to implement updateMany() in Node.js:
Step 1: Create a new project directory and initialise NPM:
npm init -y
Once you pass this command, you should see a package.json file created in your project directory.
Step 2: Create an entry point JavaScript file:
touch index.js
Step 3: Install express and ejs:
npm i mongoose express
Step 4: Open a code editor and import all the installed packages inside the index.js with the help of the require() method and set up a connection to the MongoDB database:
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);
})
Step 5: Set up a local port for the app server to listen:
app.listen(3000, () => {
console.log('Connected to PORT 3000...');
})
Step 6: Create a models folder in the project directory and inside it create product.js. Here’s where our schema will reside:
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);
Shep 7: Now, insert some documents in the database for demonstration:
db.Shoe.insertMany([
{ "_id" : 1000, "name" : "Nike Air Force 1", "price" : 4999, "sizeUK" : 6, "onSale" : false },
{ "_id" : 1001, "name" : "X Speedflow.4 Flexible Ground Boots", "price" : 5999, "sizeUK" : 7, "onSale" : true },
{ "_id" : 1002, "name" : "Men's Reebok Running Ztaur Run Shoes", "price" : 9999, "sizeUK" : 8, "onSale" : true },
{ "_id" : 1003, "name" : "Puma RS - Z Art of Sport Unisex Sneakers", "price" : 8999, "sizeUK" : 8, "onSale" : true }
])
Step 8: Using updateMany() method:
Now, let’s demonstrate the usage of the MongoDB updateMany() method on the documents inserted above:
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 pass a query to select the documents having a key “sizeUK” equal to 8 and another argument to change the “onSale” key of all the matched documents to false.
Then inside the callback, we check for the error and use the response object to print the number of documents modified by this method.
Step 9: Make sure the MongoDB server is running in the background.
Step 10: To run the application, instead of running index.js, we have to run the product.js model file because that is where our method is located:
node models/product.js
Output:
This is what our console prints:
2 items modified
This way we have successfully made use of the mongoose updatemany function using Node.js.
Conclusion
In short, if you want to update multiple documents at a time based on some given filter, the best method is updateMany(). Using updateMany() is quite easy, you just have to call it using the dot notation on the database collection object. Inside it, you have to pass query parameters and what you want to update and that’s it. You can then use the callback to catch errors or print the updated information.
Also Read: $ (update) Operator in MongoDB
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