I am relatively new to MongoDB and I am concerned that concurrent request could mutate a single document effectively causing data loss (the first write would be clobbered by the second write). DynamoDB handles this via Optimistic locking and conditional writes. Is there an equivalent in MongoDB? If not, how do you prevent concurrent request from clobbering one another?
2
Answers
@DynamoDBVersionAttribute
comes from the Java SDK, which wraps Java driver on the client side. It’s not what dynamodb provides as a database engine. From https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/enhanced/dynamodb/extensions/annotations/DynamoDbVersionAttribute.html :Similar functionality is implemented on document level in mongoose: https://thecodebarbarian.com/whats-new-in-mongoose-5-10-optimistic-concurrency.html#optimistic-concurrency-versus-versioning
Essentially it’s just monotonically incremented version number, added as a filter to the update. Document updates are atomic and binary – it either happened or not. Add the
{__v:12}
to the filter, and{__v:{$inc:1}
to update, and check number of documents updated: 1 = success, 0 = the other client already updated the document and there is nothing matching{__v:12}
condition.MongoDB FAQ: Concurrency
Vermongo: Simple Document Versioning with MongoDB
Vermongo is a simple versioning scheme for keeping older revision of MongoDB documents.
It is designed to be extremely simple and place no constraints on the type of documents that it can be applied to.
Vermongo’s optimistic concurrency control can also be used to just detect and avoid conflicting updates, even when one does not want to keep older revisions in the database.
How document versioning works