Using the .NET MongoDB API (MongoDB.Driver), what is the recommended approach for implementing optimistic concurrency control? For example, is there anything analogous to SQL Server's ROWVERSION/TIMESTAMP, e.g., a property that is automatically updated whenever the document changes? Or is there a trigger mechanism? Or any other mechanism?
Optimistic locking is a workable solution for skewed writes errors. Transactions are not enough in this case because no consistency guarantees are violated. Thanks to Spring Data MongoDB versioning and retries, it is possible to handle the situation gracefully without much boilerplate code.
MongoDB allows multiple clients to read and write the same data. To ensure consistency, MongoDB uses locking and concurrency control to prevent clients from modifying the same data simultaneously.
To have this TableAdapter employ optimistic concurrency control, simply check the "Use optimistic concurrency" checkbox. Lastly, indicate that the TableAdapter should use the data access patterns that both fill a DataTable and return a DataTable; also indicate that the DB direct methods should be created.
The following tables follow an example of optimistic concurrency. At 1:01 p.m., User2 reads the same row. At 1:03 p.m., User2 changes FirstName from "Bob" to "Robert" and updates the database. The update succeeds because the values in the database at the time of update match the original values that User2 has.
There isn't anything built-in regarding optimistic concurrency in MongoDB. You need to implement that yourself if you need it.
You can do that by adding a DateTime
timestamp, reading it before performing an update and using that timestamp as the filter for update. If the timestamp was changed before you had a chance to update than the update operation won't be able to find the document.
For example:
UpdateResult updateResult;
do
{
var document = await collection.Find(_ => _.Id == id).SingleAsync(); // Get the current document
updateResult = await collection.UpdateOneAsync(_ => _.Id == id && _.TimeStamp == document.TimeStamp, Builders<Item>.Update...); // Update the document only if the timestamp is the same
} while (updateResult.ModifiedCount == 0); // Try until an update was successfull
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