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 atomic operations 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.
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.