Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does findAndModify effectively lock the document to prevent read conflicts?

Assume there is document's structure like below:
{_id:"session-01", status:"free"}

And there are 2 concurrent operations that perform the findAndModify operation below: db.collection.findAndModify({query:{status:"free"}, update:{status:"occupied"}, new:true})

What I want to achieve is only one operation can get the "free" one, and perform lock on it, so the other operation must be getting null. Is that what the findAndModify does?

like image 337
Agung Pratama Avatar asked Nov 10 '14 14:11

Agung Pratama


People also ask

Does MongoDB have locking?

MongoDB uses multi-granularity locking [1] that allows operations to lock at the global, database or collection level, and allows for individual storage engines to implement their own concurrency control below the collection level (e.g., at the document-level in WiredTiger).

Which option should be used with findAndModify?

MongoDB – FindAndModify() Method. The findAndModify() method modifies and return a single document that matches the given criteria. By default, this method returns a pre-modification document. To return the document with the modifications made on the update, use the new option and set its value to true.

Which lock in MongoDB provides concurrency?

MongoDB uses reader-writer locks that allow concurrent readers shared access to a resource, such as a database or collection, but in MMAPv1, give exclusive access to a single write operation. WiredTiger uses optimistic concurrency control. WiredTiger uses only intent locks at the global, database and collection levels.

Which option should be used with findAndModify command to return the modified document instead of the pre modification document?

Definition. The findAndModify command modifies and returns a single document. By default, the returned document does not include the modifications made on the update. To return the document with the modifications made on the update, use the new option.


1 Answers

According to official docs, MongoDB does provide isolated update and return.
Here is the mongoDB official doc link: Why findAndModify is Atomic.
Here is a superbly illustrated example of how findAndModify works in mongoDB : How findAndModify works

Note - I usually do not enjoy posting links but I did not want to discredit the content owners.

like image 198
vmr Avatar answered Nov 11 '22 13:11

vmr