Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoose difference of findOneAndUpdate and update

What is the difference between findOneAndUpdate and update?

Both accept criteria to query and doc to update.

like image 306
SooCheng Koh Avatar asked Aug 04 '15 12:08

SooCheng Koh


People also ask

What is difference between update and findOneAndUpdate?

What is difference between update and findOneAndUpdate? The findOneAndUpdate() method returns the document after the update, whereas the updateOne() method of MongoDB also updates one document but it does not return any document.

What does findOneAndUpdate return Mongoose?

Mongoose | findOneAndUpdate() Function The findOneAndUpdate() function is used to find a matching document and update it according to the update arg, passing any options, and returns the found document (if any) to the callback.

What is findOneAndUpdate?

findOneAndUpdate() updates the first matching document in the collection that matches the filter . If no document matches the filter , no document is updated. The sort parameter can be used to influence which document is updated.

Is findOneAndUpdate Atomic?

Any findAndUpdateOne is atomic as long as it hit a single document. Thank you for your reply,i changed the question, i meant filter of update command not the findOneAndUpdate.


2 Answers

The .findOneAndUpdate method issues a mongodb .findAndModify update command and returns the found document (if any) to the callback or return the modified document rather than the original if the new option is true and the .update execute the query as an update() operation.

like image 42
styvane Avatar answered Sep 24 '22 17:09

styvane


Well there is the respective documentation to view for both .update() and .findAndModify() which is the root method of .findOneAndUpdate() here.

But in the main differences there are:

  • update(): Is meant to perform an atomic update operation against "one or more" documents matched by it's query condition in a collection. It returns the number of modified documents in it's response.

  • findOneAndUpdate(): Has the purpose of both processing an update statment on a "singular" document, as well as retrieving the content of that "singular" document. The state returned depends on the value of the "new" option as passed to the operation. Where true the "modified" document is returned. Where false the "original" document is returned before any modification. The latter form is the default option.

In short. One is meant to modify in "bulk" and not worry with the document content in result. And the other is meant to modify a singular document and return the document content in result.

That's the difference.

like image 150
Blakes Seven Avatar answered Sep 24 '22 17:09

Blakes Seven