Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB Optimistic Concurrency Control With .NET

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?

like image 600
Ricardo Peres Avatar asked Nov 25 '15 23:11

Ricardo Peres


People also ask

Does MongoDB support optimistic locking?

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.

Does MongoDB support concurrency?

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.

How do you implement optimistic concurrency control?

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.

What is an example of optimistic concurrency control?

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.


1 Answers

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
like image 127
i3arnon Avatar answered Oct 13 '22 12:10

i3arnon