0 votes
1 view
in SQL by (47.8k points)

I'm a little bit confused by the findAndModify method in MongoDB. What's the advantage of it over the update method? For me, it seems that it just returns the item first and then updates it. But why do I need to return the item first? I read the MongoDB: the definitive guide and it says that it is handy for manipulating queues and performing other operations that need get-and-set style atomicity. But I didn't understand how it achieves this. Can somebody explain this to me?

2 Answers

0 votes
by (107k points)

The difference between findAndModify and update in MongoDB is as follows, If you fetch an item and then update it, there may be an update by another thread between those two steps. If you update an item first and then fetch it, there may be another update in-between and you will get back a different item than what you updated.

0 votes
by (108k points)

Update() function can update multiple documents at a time but findAndModify() function, can only update a particular document. db.collection.findAndModify()  function will return the pre-modified version of the document, if you want to get the updated version then just pass a parameter named-’new’ as true whereas the update() function will return the modified version of the document. If you want to know more about the various operations performed on MongoDB then do refer the following crud operations in mongodb.

Related questions

Welcome to Intellipaat Community. Get your technical queries answered by top developers !