nosqlazure-cosmosdb

Cosmos DB : collection & atomic counter


I have a Cosmos DB and a collection like this one :

{
  "name" : "Marc Zukerberg",
  "follower" : "100"
}

I'm looking for a way to increment the 'follower' count, but in an ATOMIC way, because a lot of increment can occur at the same time !

Is it possible ?

Is there some patterns for such cases in NoSQL ?


Solution

  • Each document in CosmosDB has a set of System Properties.

    One of them is the etag. The etag is a property who's value changes every time the document itself changes in some way.

    This can be used to provide optimistic concurrency control.

    This can be achieved by using the AccessCondition object with your Operations such as Replace.

    That way you can guarantee that the etag matches which means that the document didn't change while you are doing your update operation.

    An example on how you can do this in detail can be found here.