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?
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).
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With