3

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?

Community
  • 1
  • 1
meso_2600
  • 1,940
  • 5
  • 25
  • 50

1 Answers1

8

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/

John Petrone
  • 26,943
  • 6
  • 63
  • 68
  • so why not just add option: return new to the Update instead of having FindAndModify ?:) – meso_2600 Jul 17 '14 at 22:32
  • it also removes too - it's not just a modification of update, think of it more as a wrapper around a query and either a remove or an update protected with a database lock. – John Petrone Jul 17 '14 at 22:34
  • for removing document I could use remove(). I guess until they add such options to update we have to use FindAndUpdate :) – meso_2600 Jul 17 '14 at 22:42
  • Thank you. Here is another question: http://stackoverflow.com/questions/24814688/mongomapper-association-skips-duplicates – meso_2600 Jul 17 '14 at 22:43