FindAndUpdate vs Update in mongodb

meso_2600 picture meso_2600 · Jul 17, 2014 · Viewed 7k times · Source

I am using Update and FindAndModify but now I have read that Update and FindAndModify are atomic(http://docs.mongodb.org/manual/tutorial/model-data-for-atomic-operations/),

So if both can do the same job, by querying for item and updating it then what is the difference?

I have found couple answers on StackOverflow but none of them mentions that Update is also atomic: What's the difference between findAndModify and update in MongoDB?

Answer

John Petrone picture John Petrone · Jul 18, 2014

The difference is that FindAndModify() returns the document, either the pre-update or post-update version, together with the update, in one atomic operation. Update is atomic but does not return the document, so if you then query for it it's possible it will have been changed by another process in the interim.

When modifying a single document, both findAndModify() and the update() method atomically update the document.

Note that this is for a single document - update can modify multiple documents, findandmodify cannot.

Also, findandmodify() can remove a document, update() cannot.

http://docs.mongodb.org/manual/reference/method/db.collection.findAndModify/