MongoDB Optimistic Concurrency Management Using .NET

Using the .NET .NET MongoDB API (MongoDB.Driver), what is the recommended approach for implementing optimistic concurrency management? For example, is there something similar to SQL Server ROWVERSION / TIMESTAMP, for example, a property that is automatically updated every time a document changes? Or is there a trigger mechanism? Or any other mechanism?

+5
source share
2 answers

MongoDB has nothing to do with optimistic concurrency. You must implement this yourself if you need it.

This can be done by adding a timestamp DateTime, reading it before performing the upgrade, and using this timestamp as a filter for updating. If the timestamp has been changed before you had the opportunity to update, than the update operation will not 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
+4
source

Since I'm too new to comment yet. This release was created https://jira.mongodb.org/browse/CSHARP-2585

0
source

Source: https://habr.com/ru/post/1617530/


All Articles