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?
Asked
Active
Viewed 4,922 times
10
-
Since I'm too newb to comment yet. Created this issue https://jira.mongodb.org/browse/CSHARP-2585 – Benjamin Lalonde Apr 12 '19 at 15:22
1 Answers
16
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

i3arnon
- 113,022
- 33
- 324
- 344
-
2Nice example :) although, generally, you should stay away from using `DateTime`s for solving technical stuff like this because it's not reliable - ["1 second per second is harder than it sounds"](https://rachelbythebay.com/w/2014/06/14/time/) comes to mind, but also simple tricky stuff like daylight saving time, can stir the notion that the clock is always increasing and will never be the same again. I recommend you use a good old `int` in a `Revision` field in your document, and then you increase it every time you perform an edit. – mookid8000 Nov 26 '15 at 09:43
-
2@mookid8000 all dates in MongoDB are in UTC, but it's a good point none the less. – i3arnon Nov 26 '15 at 09:47
-
Oh yeah, that's right - forget about dayligh saving time then ;) but clocks drifting back and forth is actually pretty common, and if your updates are frequent, you will at some point be hit by this - and in this case you would lose the other updater's edits, and you would probably never know why it happened. Subtle - and terrifying! :-o – mookid8000 Nov 26 '15 at 09:50
-
4Is this answer still the current recommended way to handle this? Or are there enhancements in MongoDb to help? – jimmy_terra Sep 12 '18 at 13:33
-
Just a hint: If updateResult.IsAcknowledged is false, accessing the updateResult.ModifiedCount will throw an exception. So before using the ModifiedCount make sure that IsAcknowledged is true. – vts123 Jul 16 '21 at 08:26