Introduction
The updateMany()
function in Mongoose is an essential tool used to modify multiple documents within a collection in a MongoDB database. This guide covers its purpose, syntax, and usage with practical examples.
Mongoose introduced updateMany()
as part of its Query API to work with MongoDB, which has evolved to include such methods in various versions, particularly post the 4.x releases.
updateMany()
is designed to update all documents that match a provided filter. This is useful for batch updates when you want to make the same change to multiple documents.
Syntax and Parameters
The basic syntax of updateMany()
is:
Model.updateMany(filter, update, [options], [callback])
The parameters are:
filter
– The selection criteria to match the documents you want to update.update
– The modifications to apply.options
(optional) – Additional options such as{ upsert: true }
to create a new document if no match is found.callback
(optional) – A function to execute upon completion. If omitted, a Promise is returned.
The returned value is a Promise if no callback is provided, resolving to an object containing the operation results.
Code Examples
Basic Usage
Update the status
field of all documents matching the filter.
const mongoose = require('mongoose');
const { Schema } = mongoose;
const userSchema = new Schema({ name: String, status: String });
const User = mongoose.model('User', userSchema);
async function updateMultipleUsers() {
await mongoose.connect('mongodb://localhost:27017/myapp');
const result = await User.updateMany({ status: 'active' }, { $set: { status: 'inactive'} });
console.log(result);
}
updateMultipleUsers();
With Options
Use upsert
option to create new documents if none match the filter.
async function updateOrInsertUsers() {
const result = await User.updateMany(
{ status: 'unknown' },
{ $set: { status: 'newcomer'} },
{ upsert: true }
);
console.log(result);
}
updateOrInsertUsers();
Conclusion
The updateMany()
function is a powerful aspect of Mongoose that allows for bulk updates to documents in a MongoDB collection. Understanding its use is key for efficient database operations.