Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update multiple documents and return all updated documents

Tags:

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

like image 825
RaR Avatar asked Feb 15 '17 10:02

RaR


People also ask

How do I update multiple columns in MongoDB?

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.

What is multi true in MongoDB?

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.

What is Upsert in MongoDB?

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.


1 Answers

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 }) 
like image 190
Jyotman Singh Avatar answered Sep 22 '22 12:09

Jyotman Singh