Documents — Data Model


    Description — Couchbase Lite concepts — Data model — Documents
    Related Content — Blobs | Documents | Indexing


    In Couchbase Lite, a document’s body takes the form of a JSON object — a collection of key/value pairs where the values can be different types of data such as numbers, strings, arrays or even nested objects. Every document is identified by a document ID, which can be automatically generated (as a UUID) or specified programmatically; the only constraints are that it must be unique within the database, and it can’t be changed.


    The following methods/initializers can be used:

    • The MutableDocument() initializer can be used to create a new document where the document ID is randomly generated by the database.

    • The MutableDocument(String id) initializer can be used to create a new document with a specific ID.

    • The database.getDocument(String id) method can be used to get a document. If it doesn’t exist in the database, it will return null. This method can be used to check if a document with a given ID already exists in the database.

    The following code example creates a document and persists it to the database.

    MutableDocument newTask = new MutableDocument();
    newTask.setString("type", "task");
    newTask.setString("owner", "todo");
    newTask.setDate("createdAt", new Date());
    try {;
    } catch (CouchbaseLiteException e) {
        Log.e(TAG, e.toString());


    When a document is read from the database it is immutable. Use the document.toMutable() method to create an updateable instance of the document.

    Document document = database.getDocument("xyz");
    MutableDocument mutableDocument = document.toMutable();
    mutableDocument.setString("name", "apples");
    try {;
    } catch (CouchbaseLiteException e) {
        Log.e(TAG, e.toString());

    Changes to the document are persisted to the database when the save method is called.

    Typed Accessors

    The Document class now offers a set of property accessors for various scalar types, including boolean, integers, floating-point and strings. These accessors take care of converting to/from JSON encoding, and make sure you get the type you’re expecting.

    In addition, as a convenience we offer Date accessors. Dates are a common data type, but JSON doesn’t natively support them, so the convention is to store them as strings in ISO-8601 format. The following example sets the date on the createdAt property and reads it back using the document.getDate(String key) accessor method.

    newTask.setValue("createdAt", new Date());
    Date date = newTask.getDate("createdAt");

    If the property doesn’t exist in the document it will return the default value for that getter method (0 for getInt, 0.0 for getFloat etc.). To check whether a given property exists in the document, you should use the Document.Contains(String key) method.

    Batch Operations

    If you’re making multiple changes to a database at once, it’s faster to group them together. The following example persists a few documents in batch.

    try {
        database.inBatch(() -> {
            for (int i = 0; i < 10; i++) {
                MutableDocument doc = new MutableDocument();
                doc.setValue("type", "user");
                doc.setValue("name", "user " + i);
                doc.setBoolean("admin", false);
                try {
                } catch (CouchbaseLiteException e) {
                    Log.e(TAG, e.toString());
                Log.i(TAG, String.format("saved user document %s", doc.getString("name")));
    } catch (CouchbaseLiteException e) {
        Log.e(TAG, e.toString());

    At the local level this operation is still transactional: no other Database instances, including ones managed by the replicator can make changes during the execution of the block, and other instances will not see partial changes. But Couchbase Mobile is a distributed system, and due to the way replication works, there’s no guarantee that Sync Gateway or other devices will receive your changes all at once.

    Document Change Events

    It’s also possible to register for document changes. The following example registers for changes to the document with ID user.john and prints the verified_account property.

        change -> {
            Document doc = database.getDocument(change.getDocumentID());
            if (doc != null) {
                Toast.makeText(context, "Status: " + doc.getString("verified_account"), Toast.LENGTH_SHORT).show();

    Document Expiration

    Document expiration allows users to set the expiration date to a document. When the document is expired, the document will be purged from the database. The purge will not be replicated to Sync Gateway.

    The following example sets the TTL for a document to 5 minutes from the current time.

    // Purge the document one day from now
    Instant ttl =, ChronoUnit.DAYS);
    database.setDocumentExpiration("doc123", new Date(ttl.toEpochMilli()));
    // Reset expiration
    database.setDocumentExpiration("doc1", null);
    // Query documents that will be expired in less than five minutes
    Instant fiveMinutesFromNow =, ChronoUnit.MINUTES);
    Query query = QueryBuilder

    Document Constraints

    Example 1. Reserved Keys List
    • _attachments

    • _id

    • _deleted

    • _removed

    • _rev