Find a document

Finds a single document in a collection using filter and sort clauses.

Result

  • Python

  • TypeScript

  • Java

  • curl

Returns a dictionary representation of a document that matches the specified filter and sort clauses, or returns None if no document was found.

The fields included in the returned document depend on the subset of fields that were requested in the projection. If requested and applicable, the document will also include a $similarity key with a numeric similarity score that represents the closeness of the sort vector and the document’s vector.

Example response:

{'_id': 101, 'name': 'John Doe', '$vector': [0.12, 0.52, 0.32]}

Returns a promise that resolves to a document that matches the specified filter and sort clauses (FoundDoc<Schema>), or to null if no document was found.

The fields included in the returned document depend on the subset of fields that were requested in the projection. If requested and applicable, the document will also include a $similarity key with a numeric similarity score that represents the closeness of the sort vector and the document’s vector.

Example response:

{'_id': 101, 'name': 'John Doe', '$vector': [0.12, 0.52, 0.32]}

Returns a document that matches the specified filter and sort clauses (Optional<T>), or returns Optional.empty() if no document was found.

The fields included in the returned document depend on the subset of fields that were requested in the projection. If requested and applicable, the document will also include a $similarity key with a numeric similarity score that represents the closeness of the sort vector and the document’s vector.

Returns a dictionary representation of a document that matches the specified filter and sort clauses, or returns null if no document was found.

The fields included in the returned document depend on the subset of fields that were requested in the projection. If requested and applicable, the document will also include a $similarity key with a numeric similarity score that represents the closeness of the sort vector and the document’s vector.

Example response:

{
  "data": {
    "document": {
      "_id": 101,
      "name": "John Doe",
      "$vector": [0.12, 0.52, 0.32]
    }
  }
}

Example null response:

{
  "data": {
    "document": null
  }
}

Parameters

  • Python

  • TypeScript

  • Java

  • curl

Name Type Summary

filter

Optional[Dict[str, Any]]

A predicate expressed as a dictionary according to the Data API filter syntax. For example: {}, {"name": "John"}, {"price": {"$lt": 100}}, {"$and": [{"name": "John"}, {"price": {"$lt": 100}}]}. For a list of available operators, see Data API operators. If you apply selective indexing when you create a collection, you can’t reference non-indexed fields in sort or filter queries.

projection

Optional[Union[Iterable[str], Dict[str, bool]]]

Select a subset of fields to include in the response for each returned document. If empty or unset, the default projection is used. The default projection doesn’t always include all document fields. For more information and examples, see Projection clauses.

include_similarity

Optional[bool]

If true, the response includes a $similarity key with the numeric similarity score that represents the closeness of the sort vector and the document’s vector. Only valid for vector search with $vector or $vectorize.

sort

Optional[Dict[str, Any]]

Use this dictionary parameter to perform a vector search or set the order in which documents are returned. For vector searches, this parameter can use either $vector or $vectorize, but not both in the same request. For more information and examples, see Sort clauses. If you apply selective indexing when you create a collection, you can’t reference non-indexed fields in sort or filter queries.

max_time_ms

Optional[int]

A timeout, in milliseconds, for the underlying HTTP request. This method uses the collection-level timeout by default.

Name Type Summary

filter

Filter<Schema>

A filter to select the document to find. For a list of available operators, see Data API operators. If you apply selective indexing when you create a collection, you can’t reference non-indexed fields in sort or filter queries.

options?

FindOneOptions

The options for this operation.

Options (FindOneOptions):

Name Type Summary

projection?

Projection

Specifies which fields to include or exclude in the returned documents. If empty or unset, the default projection is used. The default projection doesn’t always include all document fields. For more information and examples, see Projection clauses.

When specifying a projection, make sure that you handle the return type carefully. Consider type-casting.

includeSimilarity?

boolean

If true, the response includes a $similarity key with the numeric similarity score that represents the closeness of the sort vector and the document’s vector. This is only valid when performing a vector search with $vector or $vectorize.

sort?

Sort

Perform a vector search or set the order in which documents are returned. For vector searches, sort can use either $vector or $vectorize, but not both in the same request. For more information and examples, see Sort clauses. If you apply selective indexing when you create a collection, you can’t reference non-indexed fields in sort or filter queries.

maxTimeMS?

number

The maximum time in milliseconds that the client should wait for the operation to complete.

Name Type Summary

filter

Filter

Criteria list to filter the document. The filter is a JSON object that can contain any valid Data API filter expression. For a list of available operators, see Data API operators. If you apply selective indexing when you create a collection, you can’t reference non-indexed fields in sort or filter queries.

options (optional)

FindOneOptions

Set the different options for the findOne operation, including the following:

  • sort(): Perform a vector search or set the order in which documents are returned. For vector searches, this parameter can use either $vector or $vectorize, but not both in the same request. For more information and examples, see Sort clauses. If you apply selective indexing when you create a collection, you can’t reference non-indexed fields in sort or filter queries.

  • projection(): A list of flags that select a subset of fields to include in the response for each returned document. If empty or unset, the default projection is used. The default projection doesn’t always include all document fields. For more information and examples, see Projection clauses.

  • includeSimilarity(): If true, the response includes a $similarity key with the numeric similarity score that represents the closeness of the sort vector and the document’s vector. This is only valid for vector search with $vector or $vectorize.

Name Type Summary

findOne

command

The Data API command to retrieve a document in a collection based on one or more of filter, sort, projection, and options.

filter

object

An object that defines filter criteria using the Data API filter syntax. For example: {}, {"name": "John"}, {"price": {"$lt": 100}}, {"$and": [{"name": "John"}, {"price": {"$lt": 100}}]}. For a list of available operators, see Data API operators. If you apply selective indexing when you create a collection, you can’t reference non-indexed fields in sort or filter queries.

sort

object

Perform a vector search or set the order in which documents are returned. For vector searches, this parameter can use either $vector or $vectorize, but not both in the same request. For more information and examples, see Sort clauses. If you apply selective indexing when you create a collection, you can’t reference non-indexed fields in sort or filter queries.

projection

object

Select a subset of fields to include in the response for each returned document. If empty or unset, the default projection is used. The default projection doesn’t always include all document fields. For more information and examples, see Projection clauses.

options.includeSimilarity

boolean

If true, the response includes a $similarity key with the numeric similarity score that represents the closeness of the sort vector and the document’s vector. This is only valid for vector search with $vector or $vectorize.

"options": { "includeSimilarity": true }

Examples

The following examples demonstrate how to find a document in a collection.

Use a document’s ID to find a document

All documents have a unique _id property. You can use a filter to find a document with a specific _id.

  • Python

  • TypeScript

  • Java

  • curl

from astrapy import DataAPIClient

# Get an existing collection
client = DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
database = client.get_database("ASTRA_DB_API_ENDPOINT")
collection = database.get_collection("COLLECTION_NAME")

# Find a document
result = collection.find_one(
    {"_id": 101}
)

print(result)
import { DataAPIClient } from '@datastax/astra-db-ts';

// Get an existing collection
const client = new DataAPIClient('ASTRA_DB_APPLICATION_TOKEN');
const database = client.db('ASTRA_DB_API_ENDPOINT');
const collection = database.collection('COLLECTION_NAME');

// Find a document
(async function () {
  const result = await collection.findOne(
    { _id: '101' }
  );

  console.log(result);
})();
package com.datastax.astra.client.collection;

import com.datastax.astra.client.Collection;
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.model.Document;
import com.datastax.astra.client.model.Filter;
import com.datastax.astra.client.model.Filters;
import com.datastax.astra.client.model.FindOneOptions;

import java.util.Optional;

public class FindOne {

    public static void main(String[] args) {
        // Get an existing collection
        Collection<Document> collection = new DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
            .getDatabase("ASTRA_DB_API_ENDPOINT")
            .getCollection("COLLECTION_NAME");

        // Find a document
        Filter filter = Filters.eq("_id", "101");
        Optional<Document> result = collection.findOne(filter);
        System.out.println(result);
    }
}
curl -sS -L -X POST "ASTRA_DB_API_ENDPOINT/api/json/v1/ASTRA_DB_KEYSPACE/ASTRA_DB_COLLECTION" \
--header "Token: ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
  "findOne": {
    "filter": { "_id": "101" }
  }
}'

Use filters to find a document

You can use a filter to find a document that matches specific criteria. For example, you can find a document with an isCheckedOut value of false and a numberOfPages value less than 300.

For a list of available filter operators and more examples, see Data API operators.

Filters can use only indexed fields. If you apply selective indexing when you create a collection, you can’t reference non-indexed fields in a filter.

  • Python

  • TypeScript

  • Java

  • curl

from astrapy import DataAPIClient

# Get an existing collection
client = DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
database = client.get_database("ASTRA_DB_API_ENDPOINT")
collection = database.get_collection("COLLECTION_NAME")

# Find a document
result = collection.find_one(
    {
        "$and": [
            {"isCheckedOut": False},
            {"numberOfPages": {"$lt": 300}},
        ]
    }
)

print(result)
import { DataAPIClient } from '@datastax/astra-db-ts';

// Get an existing collection
const client = new DataAPIClient('ASTRA_DB_APPLICATION_TOKEN');
const database = client.db('ASTRA_DB_API_ENDPOINT');
const collection = database.collection('COLLECTION_NAME');

// Find a document
(async function () {
  const result = await collection.findOne({
    $and: [{ isCheckedOut: false }, { numberOfPages: { $lt: 300 } }],
  });

  console.log(result);
})();
package com.datastax.astra.client.collection;

import com.datastax.astra.client.Collection;
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.model.Document;
import com.datastax.astra.client.model.Filter;
import com.datastax.astra.client.model.Filters;
import com.datastax.astra.client.model.FindOneOptions;

import java.util.Optional;

public class FindOne {

    public static void main(String[] args) {
        // Get an existing collection
        Collection<Document> collection = new DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
            .getDatabase("ASTRA_DB_API_ENDPOINT")
            .getCollection("COLLECTION_NAME");

        // Find a document
        Filter filter = Filters.and(
          Filters.eq("isCheckedOut", false),
          Filters.lt("numberOfPages", 300));

        Optional<Document> result = collection.findOne(filter);

        System.out.println(result);
    }
}
curl -sS -L -X POST "ASTRA_DB_API_ENDPOINT/api/json/v1/ASTRA_DB_KEYSPACE/ASTRA_DB_COLLECTION" \
--header "Token: ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
  "findOne": {
    "filter": {"$and": [
      {"isCheckedOut": false},
      {"numberOfPages": {"$lt": 300}}
    ]}
  }
}'

Use vector search to find a document

To find the document whose $vector value is most similar to a given vector, use a sort with the vector embeddings that you want to match. For more information, see Perform a vector search.

Vector search is only available for vector-enabled collections. For more information, see Vector and vectorize.

  • Python

  • TypeScript

  • Java

  • curl

from astrapy import DataAPIClient

# Get an existing collection
client = DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
database = client.get_database("ASTRA_DB_API_ENDPOINT")
collection = database.get_collection("COLLECTION_NAME")

# Find a document
result = collection.find_one(
    {},
    sort={"$vector": [.12, .52, .32]}
)

print(result)
import { DataAPIClient } from '@datastax/astra-db-ts';

// Get an existing collection
const client = new DataAPIClient('ASTRA_DB_APPLICATION_TOKEN');
const database = client.db('ASTRA_DB_API_ENDPOINT');
const collection = database.collection('COLLECTION_NAME');

// Find a document
(async function () {
  const result = await collection.findOne(
    {},
    { sort: { $vector: [.12, .52, .32] } }
  );

  console.log(result);
})();
package com.datastax.astra.client.collection;

import com.datastax.astra.client.Collection;
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.model.Document;
import com.datastax.astra.client.model.Filter;
import com.datastax.astra.client.model.Filters;
import com.datastax.astra.client.model.FindOneOptions;

import java.util.Optional;

public class FindOne {

    public static void main(String[] args) {
        // Get an existing collection
        Collection<Document> collection = new DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
            .getDatabase("ASTRA_DB_API_ENDPOINT")
            .getCollection("COLLECTION_NAME");

        // Find a document
        FindOneOptions options = new FindOneOptions()
            .sort(new float[] {0.12f, 0.52f, 0.32f});
        Optional<Document> result = collection.findOne(options);
        System.out.println(result);
    }
}
curl -sS -L -X POST "ASTRA_DB_API_ENDPOINT/api/json/v1/ASTRA_DB_KEYSPACE/ASTRA_DB_COLLECTION" \
--header "Token: ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
  "findOne": {
    "sort": { "$vector": [.12, .52, .32] }
  }
}'

Use vector search and vectorize to find a document

To find the document whose $vector value is most similar to the $vector value of a given search string, use a sort with the search string that you want to vectorize and match. For more information, see Perform a vector search.

Vector search with vectorize is only available for collections that have vectorize enabled. For more information, see Vector and vectorize.

  • Python

  • TypeScript

  • Java

  • curl

from astrapy import DataAPIClient

# Get an existing collection
client = DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
database = client.get_database("ASTRA_DB_API_ENDPOINT")
collection = database.get_collection("COLLECTION_NAME")

# Find a document
result = collection.find_one(
    {},
    sort={"$vectorize": "Text to vectorize"}
)

print(result)
import { DataAPIClient } from '@datastax/astra-db-ts';

// Get an existing collection
const client = new DataAPIClient('ASTRA_DB_APPLICATION_TOKEN');
const database = client.db('ASTRA_DB_API_ENDPOINT');
const collection = database.collection('COLLECTION_NAME');

// Find a document
(async function () {
  const result = await collection.findOne(
    {},
    { sort: { $vectorize: "Text to vectorize" } }
  );

  console.log(result);
})();
package com.datastax.astra.client.collection;

import com.datastax.astra.client.Collection;
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.model.Document;
import com.datastax.astra.client.model.Filter;
import com.datastax.astra.client.model.Filters;
import com.datastax.astra.client.model.FindOneOptions;

import java.util.Optional;

public class FindOne {

    public static void main(String[] args) {
        // Get an existing collection
        Collection<Document> collection = new DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
            .getDatabase("ASTRA_DB_API_ENDPOINT")
            .getCollection("COLLECTION_NAME");

        // Find a document
        FindOneOptions options = new FindOneOptions()
            .sort("Text to vectorize");
        Optional<Document> result = collection.findOne(options);
        System.out.println(result);
    }
}
curl -sS -L -X POST "ASTRA_DB_API_ENDPOINT/api/json/v1/ASTRA_DB_KEYSPACE/ASTRA_DB_COLLECTION" \
--header "Token: ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
  "findOne": {
    "sort": { "$vectorize": "Text to vectorize" }
  }
}'

Use sorting to find a document

You can use a sort clause to sort documents by one or more fields.

For more information, see Sort clauses.

Sort clauses can use only indexed fields. If you apply selective indexing when you create a collection, you can’t reference non-indexed fields in sort queries.

  • Python

  • TypeScript

  • Java

  • curl

from astrapy import DataAPIClient, constants

# Get an existing collection
client = DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
database = client.get_database("ASTRA_DB_API_ENDPOINT")
collection = database.get_collection("COLLECTION_NAME")

# Find a document
result = collection.find_one(
    {"metadata.language": "English"},
    sort={
        "rating": constants.SortDocuments.ASCENDING,
        "title": constants.SortDocuments.DESCENDING,
    }
)

print(result)
import { DataAPIClient } from '@datastax/astra-db-ts';

// Get an existing collection
const client = new DataAPIClient('ASTRA_DB_APPLICATION_TOKEN');
const database = client.db('ASTRA_DB_API_ENDPOINT');
const collection = database.collection('COLLECTION_NAME');

// Find a document
(async function () {
  const result = await collection.findOne(
    { "metadata.language": "English" },
    { sort: {
      rating: 1, // ascending
      title: -1 // descending
    } }
  );

  console.log(result);
})();
package com.datastax.astra.client.collection;

import com.datastax.astra.client.Collection;
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.model.Document;
import com.datastax.astra.client.model.Filter;
import com.datastax.astra.client.model.Filters;
import com.datastax.astra.client.model.FindOneOptions;

import java.util.Optional;

public class FindOne {

    public static void main(String[] args) {
        // Get an existing collection
        Collection<Document> collection = new DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
            .getDatabase("ASTRA_DB_API_ENDPOINT")
            .getCollection("COLLECTION_NAME");

        // Find a document
        Filter filter = Filters.eq("metadata.language", "English");
        FindOneOptions options = new FindOneOptions()
            .sort(Sorts.ascending("rating"))
            .sort(Sorts.descending("title"));
        Optional<Document> result = collection.findOne(filter, options);
        System.out.println(result);
    }
}
curl -sS -L -X POST "ASTRA_DB_API_ENDPOINT/api/json/v1/ASTRA_DB_KEYSPACE/ASTRA_DB_COLLECTION" \
--header "Token: ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
  "findOne": {
    "filter": { "metadata.language": "English" },
    "sort": {
      "rating": 1,
      "title": -1
    }
  }
}'

Include the similarity score with the result

If you use a vector search to find a document, you can also include a $similarity property in the result. The $similarity value represents the closeness of the sort vector and the document’s vector.

  • Python

  • TypeScript

  • Java

  • curl

from astrapy import DataAPIClient

# Get an existing collection
client = DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
database = client.get_database("ASTRA_DB_API_ENDPOINT")
collection = database.get_collection("COLLECTION_NAME")

# Find a document
result = collection.find_one(
    {},
    sort={"$vectorize": "Text to vectorize"},
    include_similarity=True
)

print(result)
import { DataAPIClient } from '@datastax/astra-db-ts';

// Get an existing collection
const client = new DataAPIClient('ASTRA_DB_APPLICATION_TOKEN');
const database = client.db('ASTRA_DB_API_ENDPOINT');
const collection = database.collection('COLLECTION_NAME');

// Find a document
(async function () {
  const result = await collection.findOne(
    {},
    {
      sort: { $vectorize: "Text to vectorize" },
      includeSimilarity: true
    },
  );

  console.log(result);
})();
package com.datastax.astra.client.collection;

import com.datastax.astra.client.Collection;
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.model.Document;
import com.datastax.astra.client.model.Filter;
import com.datastax.astra.client.model.Filters;
import com.datastax.astra.client.model.FindOneOptions;

import java.util.Optional;

public class FindOne {

    public static void main(String[] args) {
        // Get an existing collection
        Collection<Document> collection = new DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
            .getDatabase("ASTRA_DB_API_ENDPOINT")
            .getCollection("COLLECTION_NAME");

        // Find a document
        FindOneOptions options = new FindOneOptions()
            .sort("Text to vectorize")
            .includeSimilarity();
        Optional<Document> result = collection.findOne(options);
        System.out.println(result);
    }
}
curl -sS -L -X POST "ASTRA_DB_API_ENDPOINT/api/json/v1/ASTRA_DB_KEYSPACE/ASTRA_DB_COLLECTION" \
--header "Token: ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
  "findOne": {
    "sort": { "$vectorize": "Text to vectorize" },
    "options": { "includeSimilarity": true }
  }
}'

Include only specific fields in the response

To specify which fields to include or exclude in the returned document, use a projection.

Certain fields, like $vector and $vectorize, are excluded by default and will only be returned if you specify that they should be included. Certain fields, like _id, are included by default.

  • Python

  • TypeScript

  • Java

  • curl

from astrapy import DataAPIClient

# Get an existing collection
client = DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
database = client.get_database("ASTRA_DB_API_ENDPOINT")
collection = database.get_collection("COLLECTION_NAME")

# Find a document
result = collection.find_one(
    {"metadata.language": "English"},
    projection={"isCheckedOut": True, "title": True}
)

print(result)
import { DataAPIClient } from '@datastax/astra-db-ts';

// Get an existing collection
const client = new DataAPIClient('ASTRA_DB_APPLICATION_TOKEN');
const database = client.db('ASTRA_DB_API_ENDPOINT');
const collection = database.collection('COLLECTION_NAME');

// Find a document
(async function () {
  const result = await collection.findOne(
    { "metadata.language": "English" },
    { projection: { isCheckedOut: true, title: true} },
  );

  console.log(result);
})();
package com.datastax.astra.client.collection;

import com.datastax.astra.client.Collection;
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.model.Document;
import com.datastax.astra.client.model.Filter;
import com.datastax.astra.client.model.Filters;
import com.datastax.astra.client.model.FindOneOptions;

import java.util.Optional;

public class FindOne {

    public static void main(String[] args) {
        // Get an existing collection
        Collection<Document> collection = new DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
            .getDatabase("ASTRA_DB_API_ENDPOINT")
            .getCollection("COLLECTION_NAME");

        // Find a document
        Filter filter = Filters.eq("metadata.language", "English");
        FindOneOptions options = new FindOneOptions()
            .projection(Projections.include("isCheckedOut", "title"));
        Optional<Document> result = collection.findOne(filter, options);
        System.out.println(result);
    }
}
curl -sS -L -X POST "ASTRA_DB_API_ENDPOINT/api/json/v1/ASTRA_DB_KEYSPACE/ASTRA_DB_COLLECTION" \
--header "Token: ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
  "findOne": {
    "filter": {"metadata.language": "English"},
    "projection": {"isCheckedOut": true, "title": true}
  }
}'

Exclude specific fields from the response

To specify which fields to include or exclude in the returned document, use a projection.

Certain fields, like $vector and $vectorize, are excluded by default and will only be returned if you specify that they should be included. Certain fields, like _id, are included by default.

  • Python

  • TypeScript

  • Java

  • curl

from astrapy import DataAPIClient

# Get an existing collection
client = DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
database = client.get_database("ASTRA_DB_API_ENDPOINT")
collection = database.get_collection("COLLECTION_NAME")

# Find a document
result = collection.find_one(
    {"metadata.language": "English"},
    projection={"isCheckedOut": False, "title": False}
)

print(result)
import { DataAPIClient } from '@datastax/astra-db-ts';

// Get an existing collection
const client = new DataAPIClient('ASTRA_DB_APPLICATION_TOKEN');
const database = client.db('ASTRA_DB_API_ENDPOINT');
const collection = database.collection('COLLECTION_NAME');

// Find a document
(async function () {
  const result = await collection.findOne(
    { "metadata.language": "English" },
    { projection: { isCheckedOut: false, title: false} },
  );

  console.log(result);
})();
package com.datastax.astra.client.collection;

import com.datastax.astra.client.Collection;
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.model.Document;
import com.datastax.astra.client.model.Filter;
import com.datastax.astra.client.model.Filters;
import com.datastax.astra.client.model.FindOneOptions;

import java.util.Optional;

public class FindOne {

    public static void main(String[] args) {
        // Get an existing collection
        Collection<Document> collection = new DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
            .getDatabase("ASTRA_DB_API_ENDPOINT")
            .getCollection("COLLECTION_NAME");

        // Find a document
        Filter filter = Filters.eq("metadata.language", "English");
        FindOneOptions options = new FindOneOptions()
            .projection(Projections.exclude("isCheckedOut", "title"));
        Optional<Document> result = collection.findOne(filter, options);
        System.out.println(result);
    }
}
curl -sS -L -X POST "ASTRA_DB_API_ENDPOINT/api/json/v1/ASTRA_DB_KEYSPACE/ASTRA_DB_COLLECTION" \
--header "Token: ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
  "findOne": {
    "filter": {"metadata.language": "English"},
    "projection": {"isCheckedOut": false, "title": false}
  }
}'

Use filter, sort, and projection together

  • Python

  • TypeScript

  • Java

  • curl

from astrapy import DataAPIClient, constants

# Get an existing collection
client = DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
database = client.get_database("ASTRA_DB_API_ENDPOINT")
collection = database.get_collection("COLLECTION_NAME")

# Find a document
result = collection.find_one(
    {
        "$and": [
            {"isCheckedOut": False},
            {"numberOfPages": {"$lt": 300}},
        ]
    },
    sort={
        "rating": constants.SortDocuments.ASCENDING,
        "title": constants.SortDocuments.DESCENDING,
    },
    projection={"isCheckedOut": True, "title": True}
)

print(result)
import { DataAPIClient } from '@datastax/astra-db-ts';

// Get an existing collection
const client = new DataAPIClient('ASTRA_DB_APPLICATION_TOKEN');
const database = client.db('ASTRA_DB_API_ENDPOINT');
const collection = database.collection('COLLECTION_NAME');

// Find a document
(async function () {
  const result = await collection.findOne(
    {
      $and: [{ isCheckedOut: false }, { numberOfPages: { $lt: 300 } }],
    },
    {
      sort: {
        rating: 1, // ascending
        title: -1, // descending
      },
      projection: {
        isCheckedOut: true,
        title: true,
      },
    },
  );

  console.log(result)
})();
package com.datastax.astra.client.collection;

import com.datastax.astra.client.Collection;
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.model.Document;
import com.datastax.astra.client.model.Filter;
import com.datastax.astra.client.model.Filters;
import com.datastax.astra.client.model.FindOneOptions;

import java.util.Optional;

public class FindOne {

    public static void main(String[] args) {
        // Get an existing collection
        Collection<Document> collection = new DataAPIClient("ASTRA_DB_APPLICATION_TOKEN")
            .getDatabase("ASTRA_DB_API_ENDPOINT")
            .getCollection("COLLECTION_NAME");

        // Find a document
        Filter filter = Filters.and(
          Filters.eq("isCheckedOut", false),
          Filters.lt("numberOfPages", 300));
        FindOneOptions options = new FindOneOptions()
            .sort(Sorts.ascending("rating"))
            .sort(Sorts.descending("title"))
            .projection(Projections.include("isCheckedOut", "title"));
        Optional<Document> result = collection.findOne(filter, options);
        System.out.println(result);
    }
}
curl -sS -L -X POST "ASTRA_DB_API_ENDPOINT/api/json/v1/ASTRA_DB_KEYSPACE/ASTRA_DB_COLLECTION" \
--header "Token: ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
  "findOne": {
    "filter": {"$and": [
      {"isCheckedOut": false},
      {"numberOfPages": {"$lt": 300}}
    ]},
    "sort": {
      "rating": 1,
      "title": -1
    },
    "projection": {"isCheckedOut": true, "title": true}
  }
}'

Client reference

  • Python

  • TypeScript

  • Java

  • curl

For more information, see the client reference.

For more information, see the client reference.

For more information, see the client reference.

Client reference documentation is not applicable for HTTP.

Was this helpful?

Give Feedback

How can we improve the documentation?

© 2025 DataStax | Privacy policy | Terms of use | Manage Privacy Choices

Apache, Apache Cassandra, Cassandra, Apache Tomcat, Tomcat, Apache Lucene, Apache Solr, Apache Hadoop, Hadoop, Apache Pulsar, Pulsar, Apache Spark, Spark, Apache TinkerPop, TinkerPop, Apache Kafka and Kafka are either registered trademarks or trademarks of the Apache Software Foundation or its subsidiaries in Canada, the United States and/or other countries. Kubernetes is the registered trademark of the Linux Foundation.

General Inquiries: +1 (650) 389-6000, info@datastax.com