Atomic operations

Atomic operations

Besides the basic CRUD operations such as Insert() , Replace() and Remove() , the Couchbase SDK also supports atomic operations on a document.

The following table lists the atomic operations that are supported:

Name Description
Increment Increments the value of a key by a given delta
Decrement Decrements the value of a key by a given delta
Append Appends to the back of the value of a given key
Prepend Prepends to the front of the value of a given key

Increment and decrement are often used as counters for game statistics or perhaps for tallying likes or up votes in a social media application. Here is an example of using Increment() and Decrement() :


 	static Cluster _cluster = new Cluster();

        static void Main(string[] args)
        {
            using (var bucket = _cluster.OpenBucket())
            {
                var key = "stats::counter1";
                Increment(bucket, key);
                Increment(bucket, key);
                Decrement(bucket, key);
                Decrement(bucket, key);
                Decrement(bucket, key);
            }
            _cluster.Dispose();
            Console.Read();
        }

        static void Increment(IBucket bucket, string key)
        {
            var result = bucket.Increment(key);
            if (result.Success)
            {
                Console.WriteLine(result.Content);
            }
        }

        static void Decrement(IBucket bucket, string key)
        {
            var result = bucket.Decrement(key);
            if (result.Success)
            {
                Console.WriteLine(result.Content);
            }
        }
 	

The Increment() or Decrement() operation will return the current value of the counter key after being called. Additional overloads allow a time-to-live (TTL) to be associated with a key and others allow you to control the delta of the increase or decrease and an optional starting point.

Note: The key you are incrementing or decrementing should be created by calling the Increment() or Decrement() themselves, not by using one of the other creational operations, such as Insert() or Upsert() . The reason is that the server stores the value as the ASCII representation and not as a 64-bit integer.

Decrementing the counter will not result in a negative value, instead it will be set to zero. Incrementing the counter might cause the counter to wrap.