Search code examples
javascriptnode.jsmongodbconcurrentmodification

MongoDB Concurrent read/write on single document


I'm having an issue with concurrent reads and writes on MongoDB, and was wondering if there was a simple solution embedded within the DB system.

I have an object that collects statistics for an app, and is represented on MongoDB as a single document in its own collection:

{
    "animals": {
        "cats": 0,
        "dogs": 0
}

The problem is that whenever a user adds a cat to their profile, i get the document, increase cats count and write the doc. However, if a user adds a dog just after the cat, the document read would be 0-0 and would write 0-1 instead of 1-1.

It's a typical concurrent read/write but I was wondering if there is a way to prevent this without adding my own locking system. Thanks!

Also: Cats and dogs is a simple example, I'm hosting a chat statistics db (messages sent, received, error...).

Not related: Issue with single document concurrent read and write operations in mongodb / node.js


Solution

  • In this particular case, you could use the increment operator $inc (https://docs.mongodb.com/manual/reference/operator/update/inc/) instead of a read followed by a write.

    $inc is an atomic operation, and hence should not case the issue you have with read, and then writing