Currently I am trying to understand how to implement a CAS operation in mongodb properly to support optimistic locking. I've found out that updates in mongodb
are atomic but I am not sure what this means (only the document rewrite is atomic or all cycle of update, including search for corresponding document and its rewriting, is atomic?). Lets consider following example.
_id
value set to 123 and has attribute cas_val
set to 10.cas_val
of the document with _id
equal to 123 to 11.cas_val
of the document with _id
equal to 123 to 11. So, is it possible that both operation succeed in case when no other updates to the document with _id
123 were performed?
P.S. Is there some build in technique in mongodb
for the optimistic locking scenario?
The correct technique for optimistic locking is to use the "update if current" which is described in detail in MongoDB docs.
The key to this technique is that the update condition cannot simply be {_id:123}
but rather it has to be {_id:123, cas_val: 10}
and the update clause would $set appropriate fields including incrementing the cas_val to 11.
Now the thread that "loses" the race and arrives second will NOT find a matching document to update and will need to "retry" by refetching the document (now with cas_val 11) and trying again. The way you find out if the update succeeded or not is by checking the writeConcern structure (it will indicate how many records were affected in "n" and whether existing record was updated in "updatedExisting" field).
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