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?
8
votes
1 Answers
13
votes
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