Count documents

Counts documents in a collection using filter and sort clauses.

Exact counting of the number of documents is a slow, expensive operation. If the document count exceeds the upper limit set by you or by the API, an indication of this limit will be returned instead of the full count.

If you need to count large numbers of documents, consider using the method to estimate count or the DataStax Bulk Loader instead.

Method signature

  • Python

  • TypeScript

  • Java

  • curl

collection.count_documents(
    filter: Dict[str, Any],
    *,
    upper_bound: int,
    max_time_ms: int,
) -> int:
collection.countDocuments(
  filter: Filter<Schema>,
  upperBound: number,
  options?: {
    maxTimeMS?: number,
  },
): Promise<number>
int countDocuments(
  int upperBound
)
int countDocuments(
  Filter filter,
  int upperBound
)
int countDocuments(
  Filter filter,
  int upperBound,
  CountDocumentsOptions options
)
curl -sS -L -X POST "ASTRA_DB_API_ENDPOINT/api/json/v1/ASTRA_DB_KEYSPACE/COLLECTION_NAME" \
--header "Token: ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
  "countDocuments": {
    "filter": FILTER
  }
}'

Result

  • Python

  • TypeScript

  • Java

  • curl

Returns an integer indicating the exact number of documents that match the specified filter.

If the count exceeds the caller-provided or API-set upper bound, the client raises TooManyDocumentsToCountException.

Returns a promise that resolves to an integer indicating the exact number of documents that match the specified filter.

If the count exceeds the caller-provided or API-set upper bound, the client raises TooManyDocumentsToCountError.

Returns an integer indicating the exact number of documents that match the specified filter.

If the count exceeds the caller-provided or API-set upper bound, the client raises TooManyDocumentsToCountException.

The response includes a status.count property, which is an integer indicating the exact number of documents that match the specified filter.

If the count exceeds the upper bound set by the API, then the status.count value will be the upper bound, and the status.moreData value is true.

Example response:

{
  "status": {
    "count": 105
  }
}

Example response if the number of documents exceeds the upper bound.

{
  "status": {
    "moreData": true,
    "count": 1000
  }
}

Parameters

  • Python

  • TypeScript

  • Java

  • curl

Name Type Summary

filter

Dict[str, Any]

An object that defines filter criteria using the Data API filter syntax. The method only finds documents that match the filter criteria.

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.

upper_bound

int

The maximum number of documents to count.

If the actual number of documents exceeds this value or exceeds the limit set by the Data API, the client will raise an error.

max_time_ms

int

Optional. The maximum time, in milliseconds, that the client should wait for the underlying HTTP request.

Default: The default value for the collection. This default is 30 seconds unless you specified a different default when you initialized the Collection object.

Name Type Summary

filter

Filter<Schema>

An object that defines filter criteria using the Data API filter syntax. The method only finds documents that match the filter criteria.

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.

upperBound

number

The maximum number of documents to count.

If the actual number of documents exceeds this value or exceeds the limit set by the Data API, the client will raise an error.

options?

WithTimeout

Optional. The options for this operation. See the options table for more details.

Properties of options

Name

Type

Summary

maxTimeMS

number

Optional. The maximum time, in milliseconds, that the client should wait for each underlying HTTP request.

Default: The default value for the collection. This default is 30 seconds unless you specified a different default when you initialized the Collection object.

Name Type Summary

filter

Filter

Optional. An object that defines filter criteria using the Data API filter syntax. The method only finds documents that match the filter criteria.

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.

upperBound

int

The maximum number of documents to count.

If the actual number of documents exceeds this value or exceeds the limit set by the Data API, the client will raise an error.

options

CountDocumentsOptions

Optional. The options for this operation. This class does not include any methods that are specific to the countDocuments method.

Use the countDocuments command with these parameters:

Name Type Summary

filter

object

An object that defines filter criteria using the Data API filter syntax. The method only finds documents that match the filter criteria.

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.

Examples

The following examples demonstrate how to count documents in a collection.

Count documents that match a filter

You can use a filter to count documents that match specific criteria.

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, exceptions

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

# Count documents
try:
  result = collection.count_documents(
    {
        "$and": [
            {"isCheckedOut": False},
            {"numberOfPages": {"$lt": 300}},
        ]
    },
    upper_bound=500
  )
  print(result)
except(exceptions.TooManyDocumentsToCountException):
    print("Number of documents exceeds upper bound or API limit")
import { DataAPIClient, TooManyDocumentsToCountError } 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');

(async function () {
  try {
    // Count documents
    const result = await collection.countDocuments(
      {
        $and: [{ isCheckedOut: false }, { numberOfPages: { $lt: 300 } }],
      },
      500,
    );

    console.log(result);
  } catch (TooManyDocumentsToCountError) {
    console.log("Number of documents exceeds upper bound or API limit");
  }
})();
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;

public class CountDocuments {

    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");

        // Count documents
        Filter filter =
            Filters.and(Filters.eq("isCheckedOut", false), Filters.lt("numberOfPages", 300));

        try {
          Integer result = collection.countDocuments(filter, 500);
          System.out.println(result);
        } catch (TooManyDocumentsToCountException error) {
            System.out.println("Number of documents exceeds upper bound or API limit");
        }
    }
}
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 '{
  "countDocuments": {
    "filter": {"$and": [
      {"isCheckedOut": false},
      {"numberOfPages": {"$lt": 300}}
    ]}
  }
}'

Count all documents

To attempt to count all documents, use an empty filter.

  • Python

  • TypeScript

  • Java

  • curl

from astrapy import DataAPIClient, exceptions

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

# Count documents
try:
  result = collection.count_documents(
    {},
    upper_bound=500
  )
  print(result)
except(exceptions.TooManyDocumentsToCountException):
    print("Number of documents exceeds upper bound or API limit")
import { DataAPIClient, TooManyDocumentsToCountError } 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');

(async function () {
  try {
    // Count documents
    const result = await collection.countDocuments(
      {},
      500,
    );

    console.log(result);
  } catch (TooManyDocumentsToCountError) {
    console.log("Number of documents exceeds upper bound or API limit");
  }
})();
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;

public class CountDocuments {

    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");

        // Count documents
        try {
          Integer result = collection.countDocuments(500);
          System.out.println(result);
        } catch (TooManyDocumentsToCountException error) {
            System.out.println("Number of documents exceeds upper bound or API limit");
        }
    }
}
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 '{
  "countDocuments": {
    "filter": {}
  }
}'

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