MongoDB Optimistic Locking Retry
MongoDB Optimistic Locking Retry
Suppose I have multiple clients and all are hooked to the same Mongo Database. Each document has a version number to ensure that data isn't lost.
Document #1
{
__v: 0,
_id: 1,
quantity: 5
}
An update hits the server to update the document to quantity 10, using __v as 0.
Collection.update({_id: 1, __v: 0}, {$set: {quantity: 10}, $inc: {__v: 1}});
Now just say that another updates comes in right after as the following:
Collection.update({_id: 1, __v: 0}, {$set: {quantity: 15}, $inc: {__v: 1}});
Since the __v of the update is not 1, this update does not happen, so the client receives an error. This is what I am attempting to resolve.
Issue #1
Merging the 2nd update with the old __v: 0 document could work if the properties don't conflict, but if they do like in this example, not sure how to solve this issue.
I am thinking maybe I could keep the history of the documents, somehow compare the update with the version number (the second so quantity of 15 minus initial document quantity of 5, get an $inc of 10), and then take the latest document version of quantity 10 and $inc 10 to get a total of 20? Not sure if this is a bad idea. What about nested arrays getting deleted/pushed?
Issue #2
Say I am updating 3 different collections and need all 3 to either work or all 3 to fail (they need to be in sync). So what happens if two updates to collections work and then the third fails, I need to roll back the other two collection updates so they remain in sync.
I am using the oplog to attempt to get "live" data, but there are situations where two updates may happen before the live data responds to the clients and I am trying to prevent the user from getting error messages and rather deal with these updates on the server.
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.