skip to Main Content

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


  1. @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 :

    Every time a record with this attribute is written to the database it will be incremented and a condition added to the request to check for an exact match of the old version.

    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.

    Login or Signup to reply.
  2. MongoDB FAQ: 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. Writes to
    a single document occur either in full or not at all, and clients
    always see consistent data.


    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

    MongoDB provides no out-of-the-box concurrency control. A common
    pattern for supporting concurrency is using a document version number
    (int) that is used as a filter for update statements

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search