A newer version of this documentation is available.

View Latest

Atomic Counters

You can atomically increment or decrement the numerical value of special counter documents
counter(docid, value)
counter(docid, -value)

A document may be used as a counter if its value is a simple ASCII number, like 42. Couchbase allows you to atomically increment and decrement these values using a special counter command. The example below (in Python) shows how to use counters:

>>> cb.counter('counter_id', delta=20, initial=100).value
>>> cb.counter('counter_id', delta=1).value
>>> cb.counter('counter_id', delta=-50).value

A counter can be created by using the counter() function with an initial value. The initial value is the value the counter uses if the counter ID does not yet exist.

Once created, the counter can be incremented or decremented atomically by a given amount or delta. Specifying a positive delta increments the value and specifying a negative one decrements it. When a counter operation is complete, the application receives the current value of the counter, after the increment.

Couchbase counters are 64-bit unsigned integers in Couchbase, and do not wrap around if decremented beyond 0, however they will wrap around if incremented past their maximum value (which is the maximum value contained within a 64 bit integer). Many SDKs will limit the delta argument to the value of a signed 64 bit integer.

Expiration times can also be specified when using counter operations.

CAS values are not used with counter operations since counter operations are atomic. The intent of the counter operation is to simply increment the current server-side value of the document. If you wish to only increment the document if it is at a certain value, then you may use a normal upsert function with CAS:

rv = cb.get('counter_id')
value, cas = rv.value, rv.cas
if should_increment_value(value):
  cb.upsert('counter_id', value + increment_amount, cas=cas)

Counter in other SDKs

C | Python | Java | .NET | Go | node.js