Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between findAndModify and findOneAndUpdate?

Tags:

mongodb

It seems they are the same. But is there any really difference between the two? The only obvious thing is of the findOneAndUpdate() which will only match to one document.

like image 674
isemaj Avatar asked Nov 19 '18 12:11

isemaj


2 Answers

findOneAndUpdate updates the very first document based on the filter criteria. With findAndModify you can do a lot more. You can update as well as remove the documents matching the filter criteria. Please have a look at below links for more details: https://docs.mongodb.com/manual/reference/method/db.collection.findAndModify/ https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndUpdate/

like image 135
Sandeep Avatar answered Sep 18 '22 19:09

Sandeep


Besides what you mentioned, the most conspicuous difference is:

findOneAndUpdate allows for just updates - no deletes or replaces etc.

findAndModify can do a lot more including replace, delete and so on. It combines the functionality of three DML operations: update, delete, replace. So it can be used as such.

Disadvantage is that it is prone to errors precisely because it combines three DML operations.

Similarities:

  • They both operate on a single document
  • And return that updated document - provided it could match one

History:

findOneAndUpdate, findOneAndReplace, findOneAndDelete are the 3 more recent methods introduced in version 3.2 of the shell to circumvent the issues mentioned above with findAndModify.

like image 39
Khanna111 Avatar answered Sep 19 '22 19:09

Khanna111