I am looking for a way to update many documents at once using mongoose
and return all the modified documents. I tried with setting multi:true
in update(). It is updating all matching documents but not returning any. Then I tried with findOneAndUpdate(). It is updating and returning only one document even if there are many matching ones. Yeah, the function name itself tells, it will update only one, still I tried. I could not set option like multi:true
in findOneAndUpdate()
. How can it be done? Thanks in advance
Update Multiple Fields of a Single Document. We can use $set and $inc operators to update any field in MongoDB. The $set operator will set the newly specified value while the $inc operator will increase the value by a specified value.
To update multiple documents in a collection, set the multi option to true. multi is optional. If set to true, updates multiple documents that meet the query criteria. If set to false, updates one document.
In MongoDB, upsert is a method that is used to insert and update the value in any operation. In other words, the MongoDB upsert method is a combination of insert and update (insert + update = upsert). By default, the upsert method's value is always false.
Currently I don't think its possible in MongoDB to update multiple documents and return all the updated documents in the same query.
In Mongoose, the findOneAndUpdate()
is based on the native findAndModify()
method of MongoDB.
If you check the offical documentation of the findAndModify()
method, its states that -
The findAndModify command modifies and returns a single document.
Although the query may match multiple documents, findAndModify will only select one document to modify.
Hence, you can not update multiple documents using findAndModify
.
update()
or updateMany()
method on the other hand updates many documents with the multi
flag but it only returns the WriteResult which looks like this -
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With