When working on a MongoDB database using Mongoose, there will come a time when documents in a collection need to be updated. It could just be a single document, or it could be more than one. For the latter situation, updateMany()
is the right query method to use.
In summary, the updateMany()
function helps to update many documents that match a particular filter in Mongoose.
Model.updateMany({filter}, {update})
filter
: The filter is the match for documents that you wish to update. Every document that matches the filter will be updated. An example is {category: "food"}
. This is a filter to match documents with the category
field "food"
.
update
: This is also an object that contains what needs to be updated in the documents matched.
callback
: It can also take a callback function if you wish to do something to documents after they are returned.
The updateMany()
function returns a query which is a write result. The write result contains the number of documents matched, the number of documents modified, etc.
In the example below, a Schema
is created and thereafter a query is made. The query is made with the updateMany()
method. Finally, we log the result returned to the console.
// import mongooseconst mongoose = require("mongoose");// creating a Schema with mongooselet Item = mongoose.model("Item", new mongoose.Schema({name: String,category: Number,price: Number,tag: String}))// make a query with the `updateMany()` functionconst items = await Item.updateMany({ category: "food" }, { tag: "food" })console.log(items)/*OUTPUT : items contains the following:{matchedDocument: NumbermodifiedCount: Number,acknowledged: Boolean,upsertedId: Null or an id,upsertedCount: Number}*/
In the example above, when the upateMany()
function is called on the Item
collection together with the filter and the update, the result is logged to the console. The result contains the following:
matchedDocument
: This is the number of documents matched.modifiedCount
: This is the number of documents modified.acknowledged
: This is a boolean that tells us if the operation was successful. A true
means a success and a false
means otherwise.upsertedId
: This is either a null or an id. It is the document upserted.upsertedCount
: This is the number of documents upserted.