How to Use Mongoose's updateMany() Function
Nov 2, 2021
If you want to update several documents with one command in Mongoose, you should use the updateMany()
function.
It takes up to three parameters:
- filter: what documents it should find that match the filter. You can omit this parameter if you want to update all the documents in the model
- update: a description of the updates to apply using update operators
- options: other tuneable parameters
const testSchema = new mongoose.Schema({
name: String,
location: String
});
const Test = mongoose.model('Test', testSchema);
await Test.create({ name: 'Test Testerson' });
await Test.create({ name: 'Mastering JS' });
await Test.create({ name: 'MeanIT' });
// Set `location` property on all documents
await Test.updateMany({}, { location: 'Florida' });
// Set `location` property on documents whose 'name' starts with 'M'
await Test.updateMany({ name: /^M/ }, { $set: { location: 'Miami' } });
Return Value
await Model.updateMany()
returns an object with 5 properties:
acknowledged
: a boolean indicating whether the update operation was acknowledged by the server. See write concerns.modifiedCount
: the number of documents that were updated. Only documents that were updated will be included in this count. For example, if you were changing the name of all the documents toTest
but some documents already had the nameTest
, those documents would not be included in that count.upsertedId
: will either benull
or contain an id if a document had to be upserted.upsertedCount
: will reflect the number of documents that had to be upserted.matchedCount
: the number of documents that matched the filter.
await Test.updateMany({}, { location: 'Florida' });
// { acknowledged: true, modifiedCount: 3, upsertedId: null, upsertedCount: 0, matchedCount: 3 }
modifiedCount
will always be less than or equal to matchedCount
.
modifiedCount
may be less if some documents were unaffected by the update.
For example, if you run the above update twice, the second time modifiedCount
will be 0 because all documents already have location
set to 'Florida'.
await Test.updateMany({}, { location: 'Florida' });
const res2 = await Test.updateMany({}, { location: 'Florida' });
res2.matchedCount; // 3
res2.modifiedCount; // 0, because no documents were changed
Want to become your team's MongoDB expert? "Mastering Mongoose" distills 8 years of hard-earned
lessons building Mongoose apps at scale into 153 pages. That means you can learn what you need
to know to build production-ready full-stack apps with Node.js and MongoDB in a few days.
Get your copy!
Did you find this tutorial useful? Say thanks by starring our repo on GitHub!