Key Value Operations

Documents

A document refers to an entry in the database (other databases may refer to the same concept as a row). A document has an ID (primary key in other databases), which is unique to the document and by which it can be located. The document also has a value which contains the actual application data. See the concept guide to Documents for a deeper dive into documents in the Couchbase Data Platform. Or read on, for a hands-on introduction to working with documents from the Node.js SDK.

CRUD Operations

The core interface to Couchbase Server is simple KV operations on full documents. Make sure you’re familiar with the basics of authorization and connecting to a Cluster from the Start Using the SDK section. We’re going to expand on the short Upsert example we used there, adding options as we move through the various CRUD operations. Here is the Insert operation at its simplest:

Insert
const result = await collection.insert(key, document);

Options may be added to operations:

Insert (with options)
const result = await collection.insert(key, document, {
    timeout: 10000, // 10 seconds
});

Setting a Compare and Swap (CAS) value is a form of optimistic locking - dealt with in depth in the CAS page. Here we just note that the CAS is a value representing the current state of an item; each time the item is modified, its CAS changes. The CAS value is returned as part of a document’s metadata whenever a document is accessed.

timeout is an optional parameter which is represented in milliseconds. Timeout sets the timeout value for the operation. We will add to these options for the Replace example:

const result = await collection.replace(key,
    document, {
        cas: cas,
        expiration: 60, // 60 seconds
        timeout: 5000, // 5 seconds
    });

Expiration sets an explicit time to live (TTL) for a document, for which you can also see a more detailed example of TTL discovery later in the docs. We’ll discuss modifying Expiration in more details below. For a discussion of item (Document) vs Bucket expiration, see the Expiration Overview page.

Durability

let result = await collection.upsert(key, document, {
    expiration: 60, // 60 seconds
    durabilityPersistTo: 1,
    durabilityReplicateTo: 0, // anything but 0 will fail on single-node cluster
    timeout: 5000, // 5 seconds
});

Here, we have add Durability options, namely persistTo and replicateTo. In Couchbase Server releases before 6.5, Durability was set with these two options — see the 6.0 Durability documentation — covering how many replicas the operation must be propagated to and how many persisted copies of the modified record must exist.

If 6.5 or above is being used, you can take advantage of the Durable Write feature, in which Couchbase Server will only return success to the SDK after the requested replication level has been achieved. The three replication levels are:

  • Majority - The server will ensure that the change is available in memory on the majority of configured replicas.

  • MajorityAndPersistToActive - Majority level, plus persisted to disk on the active node.

  • PersistToMajority - Majority level, plus persisted to disk on the majority of configured replicas.

The options are in increasing levels of safety. Note that nothing comes for free - for a given node, waiting for writes to storage is considerably slower than waiting for it to be available in-memory. These trade offs, as well as which settings may be tuned, are discussed in the durability page.

The following example demonstrates using the newer durability features available in Couchbase server 6.5 onwards.

let result = await collection.upsert(key, document, {
    expiration: 60, // 60 seconds,
    durabilityLevel: couchbase.DurabilityLevel.None, // Majority etc.
    timeout: 5000, // 5 seconds
});

To stress, durability is a useful feature but should not be the default for most applications, as there is a performance consideration, and the default level of safety provided by Couchbase will be reasonable for the majority of situations.

Sub-Document Operations

All of these operations involve fetching the complete document from the Cluster. Where the number of operations or other circumstances make bandwidth a significant issue, the SDK can work on just a specific path of the document with Sub-Document Operations.

Retrieving full documents

Using the get() method with the document key can be done in a similar fashion to the other operations:

const result = await collection.get(key);

Timeout can also be set - as in the earlier Insert example:

Get (with options)
return collection.get(key, {timeout: 1000},
    (err, res) => {
        if (res) {
            document = res.value;
            cas = res.cas;
        }
    }).catch((e) => {
    console.log(e);
    return h.response(e.toString() + "<pre>" + e.stack + "</pre>");
});

Removing

When removing a document, you will have the same concern for durability as with any additive modification to the Bucket:

Remove (with options)
const result = await collection.remove(key, {
    cas: cas,
    persistTo: 1,
    replicateTo: 1,
    timeout: 5000, // 5 seconds
});

Expiration / TTL

By default, Couchbase documents do not expire, but transient or temporary data may be needed for user sessions, caches, or other temporary documents. Using touch(), you can set expiration values on documents to handle transient data:

const result = await collection.touch(key, 10000);

A network timeout can be set with the options, in the same fashion as earlier examples on this page:

const result = await collection.touch(key, 30000, {
    timeout: 5000, // 5 seconds
});

Atomic document modifications

The value of a document can be increased or decreased atomically using binary().increment() and binary().decrement().

Increment
// increment binary value by 1
const result = await collection.binary().increment(binValKey, 1);
Increment (with options)
// increment binary value by 1, if binValKey doesn’t exist, seed it at 1000
const result = await collection.binary().increment(binValKey, 1,
    {initial: 1000, timeout: 5000},
    (err, res) => {
        console.log("res: " + JSON.stringify(res));
    });
Decrement
// decrement binary value by 1
const result = await collection.binary().decrement(binValKey, 1);
Decrement (with options)
// decrement binary value by 1, if binValKey doesn’t exist, seed it at 1000
const result = await collection.binary().decrement(binValKey, 1, {
    initial: 1000,
    timeout: 5000
});
Increment & Decrement are considered part of the ‘binary’ API and as such may still be subject to change

Additional Resources

Working on just a specific path within a JSON document will reduce network bandwidth requirements - see the Sub-Document pages. For working with metadata on a document, reference our Extended Attributes pages.

Our Query Engine enables retrieval of information using the SQL-like syntax of N1QL.