Read Documents

  • how-to
    +
    How to read documents with a command line tool or an SDK.

    Introduction

    Retrieving documents by ID is the fastest and simplest way to read data in Couchbase. The Key-Value (KV) or Data Service allows you to retrieve a full document when you need to fetch all of the data stored. However, in instances where this can be costly and unnecessary, Couchbase also provides access to specific paths within a document.

    Read the following for further information about the clients available:

    Please note that the examples in this guide will alter the data in your sample database. To restore your sample data, remove and reinstall the travel sample data. Refer to Import Data with the Capella UI for details.

    Reading a Document

    To read a single document in Couchbase, perform a get operation.

    • .NET

    • Java

    • Node.js

    • Python

    Use the GetAsync() method to retrieve a document by ID.

    A GetResult object is returned, which includes the content, cas value, and other valuable metadata.


    The example below retrieves document hotel-123 from the hotel keyspace in the inventory scope.

    var getResult = await hotelCollection.GetAsync("hotel-123");
    
    // Print some result metadata to the console.
    Console.WriteLine($"CAS: {getResult.Cas}");
    Console.WriteLine($"Data: {getResult.ContentAs<JObject>()}");
    If the document doesn’t exist, the SDK will return a DocumentNotFoundException error.

    Click the View button to see this code in context.

    For further details, refer to CollectionExtensions.

    Use the get() method to retrieve a document by ID.

    A GetResult object is returned, which includes the content, cas value, and other valuable metadata.


    The example below retrieves document hotel-123 from the hotel keyspace in the inventory scope.

    GetResult getResult = hotelCollection.get("hotel-123");
    
    // Print the result's CAS metadata to the console.
    System.out.println("CAS:" + getResult.cas());
    If the document doesn’t exist, the SDK will return a DocumentNotFoundException error.

    Click the View button to see this code in context.

    For further details, refer to Collection.

    Use the get() function to retrieve a document by ID.

    A GetResult promise is returned, which includes the content, cas value, and other valuable metadata.


    The example below retrieves document hotel-123 from the hotel keyspace in the inventory scope.

    const getResult = await hotelCollection.get('hotel-123')
    
    // Print some result metadata to the console.
    console.log('CAS:', getResult.cas)
    console.log('Data:', JSON.stringify(getResult.content, null, '  '))
    If the document doesn’t exist, the SDK will return a DocumentNotFoundError error.

    Click the View button to see this code in context.

    For further details, refer to Collection.

    Use the get() function to retrieve a document by ID.

    A GetResult object is returned, which includes the content, cas value, and other valuable metadata.


    The example below retrieves document hotel-123 from the hotel keyspace in the inventory scope.

    get_result = hotel_collection.get("hotel-123")
    
    # Print some result metadata to the console.
    print("CAS:", get_result.cas)
    print("Data: {}".format(get_result.content_as[dict]))
    If the document doesn’t exist, the SDK will return a DocumentNotFoundException error.

    Click the View button to see this code in context.

    For further details, refer to Collection.

    Reading with Options

    To specify further parameters, such as expiry, add options to the get operation.

    • .NET

    • Java

    • Node.js

    • Python

    Pass any required options to the GetAsync() method when retrieving a document.

    A GetResult object is returned, which may include extra metadata, depending on the options passed.


    The example below retrieves a document hotel-123 with additional expiry metadata.

    var getResult = await hotelCollection.GetAsync("hotel-456", options =>
    {
    	options.Expiry();
    });
    
    // Print some result metadata to the console.
    Console.WriteLine($"CAS: {getResult.Cas}");
    Console.WriteLine($"Data: {getResult.ContentAs<JObject>()}");
    Console.WriteLine($"Expiry: {getResult.ExpiryTime}");

    Click the View button to see this code in context.

    For further details, refer to CollectionExtensions.

    Pass any required options to the get() method when retrieving a document.

    A GetResult object is returned, which may include extra metadata, depending on the options passed.


    The example below retrieves a document hotel-123 with additional expiry metadata.

    GetResult getResult = hotelCollection.get("hotel-123", 
        GetOptions.getOptions().withExpiry(true)
    );
    
    // Print the result's CAS metadata to the console.
    System.out.println("CAS:" + getResult.cas());
    System.out.println("Data:" + getResult.contentAsObject());
    System.out.println("Expiry:" + getResult.expiryTime());

    Click the View button to see this code in context.

    For further details, refer to Collection.

    Pass any required options to the get() method when retrieving a document.

    A GetResult object is returned, which may include extra metadata, depending on the options passed.


    The example below retrieves a document hotel-123 with additional expiry metadata.

    const getResult = await hotelCollection.get('hotel-456', {
      withExpiry: true,
    })
    
    // Print some result metadata to the console.
    console.log('CAS:', getResult.cas)
    console.log('Data:', JSON.stringify(getResult.content, null, '  '))
    console.log('Expiry time:', getResult.expiryTime)

    Click the View button to see this code in context.

    For further details, refer to Collection.

    Pass any required options to the get() method when retrieving a document.

    A GetResult object is returned, which may include extra metadata, depending on the options passed.


    The example below retrieves a document hotel-123 with additional expiry metadata.

    get_result = hotel_collection.get(
        "hotel-456", GetOptions(with_expiry=True)
    )
    
    # Print some result metadata to the console.
    print("CAS:", get_result.cas)
    print("Data: {}".format(get_result.content_as[dict]))
    print("Expiry time: {}".format(get_result.expiryTime))

    Click the View button to see this code in context.

    For further details, refer to Collection.

    Reading a Sub-Document

    JSON documents can contain a lot of nested data — which might not necessarily need to be accessed all at once. Reading full documents to access a field or two is not ideal and could cause performance issues in your application. Instead, a better practice would be to access specific paths, or sub-documents, to perform more efficient read operations.

    To fetch a specific field inside a document, you can perform a sub-document get operation.

    • .NET

    • Java

    • Node.js

    • Python

    1. Call the LookupInAsync() method, which takes a document ID and an IEnumerable containing LookUpInSpec objects.

    2. Use the LookUpInSpec object to specify the sub-operation to be performed within the lookup.

    A LookupInResult object is returned, containing the result and metadata relevant to the sub-document get operation.


    The example below fetches the geo data from the hotel-123 document.

    var lookupInResult = await hotelCollection.LookupInAsync("hotel-123",
    		specs => specs.Get("geo")
    );
    
    Console.WriteLine($"CAS: {lookupInResult.Cas}");
    Console.WriteLine($"Geo: {lookupInResult.ContentAs<JObject>(0)}");

    Click the View button to see this code in context.

    For further details, refer to CollectionExtensions.

    1. Call the lookupIn() method, which takes a document ID and an array of LookUpInSpec objects.

    2. Use the LookUpInSpec object to specify the sub-operation to be performed within the lookup.

    A LookupInResult object is returned, containing the result and metadata relevant to the sub-document get operation.


    The example below fetches the geo data from the hotel-123 document.

    List<LookupInSpec> specs = Arrays.asList(LookupInSpec.get("geo"));
    
    LookupInResult lookupInResult = hotelCollection.lookupIn("hotel-123", specs);
    System.out.println("CAS:" + lookupInResult.cas());
    System.out.println("Geo:" + lookupInResult.contentAsObject(0));
    If the document path can’t be found, the SDK will return a PathNotFoundException error.

    Click the View button to see this code in context.

    For further details, refer to Collection.

    1. Call the lookupIn() function, which takes a document ID and an array of LookUpInSpec objects.

    2. Use the LookUpInSpec object to specify the sub-operation to be performed within the lookup.

    A LookupInResult promise is returned containing the result and metadata relevant to the sub-document get operation.


    The example below fetches the geo data from the hotel-123 document.

    const lookupInResult = await hotelCollection.lookupIn('hotel-123', [
      couchbase.LookupInSpec.get('geo'),
    ])
    console.log('CAS:', lookupInResult.cas)
    console.log('Geo:', lookupInResult.content[0].value)

    Click the View button to see this code in context.

    For further details, refer to Collection.

    1. Call the lookup_in() function, which takes a document ID and a list of LookUpInSpec objects.

    2. Use the LookUpInSpec object to represent the sub-operation to be performed within the lookup.

    A LookupInResult object is returned containing the result and metadata relevant to the sub-document get operation.


    The example below fetches the geo data from the hotel-123 document.

    lookup_in_result = hotel_collection.lookup_in(
        "hotel-123", [subdocument.get("geo")]
    )
    print("CAS:", lookup_in_result.cas)
    print("Data:", lookup_in_result.content_as[dict](0))
    If the document path can’t be found, the SDK will return a PathNotFoundException error.

    Click the View button to see this code in context.

    For further details, refer to Collection.

    Key-Value Operations with SDKs:

    Sub-Document operations with SDKs: