Docs Menu

Docs HomeDevelop ApplicationsMongoDB DriversJava Sync Driver

Count Documents

There are two instance methods in the MongoCollection class that you can call to count the number of documents in a collection:

  • countDocuments() returns the number of documents in the collection that match a specified query. If you specify an empty query filter, the method returns the total number of documents in the collection.

  • estimatedDocumentCount() returns an estimation of the number of documents in the collection based on the collection metadata. You cannot specify a query when using this method.

The estimatedDocumentCount() method returns more quickly than the countDocuments() method because it uses the collection's metadata rather than scanning the entire collection. The countDocuments() method returns an accurate count of the number of documents and supports specifying a filter.

Tip

When using countDocuments() to return the total number of documents in a collection, you can improve performance by avoiding a collection scan. To do this, use a hint to take advantage of the built-in index on the _id field. Use this technique only when calling countDocuments() with an empty query parameter.

CountOptions opts = new CountOptions().hintString("_id_");
long numDocuments = collection.countDocuments(new BsonDocument(), opts);

When you call the countDocuments() method, you can optionally pass a query filter parameter. You cannot pass any parameters when you call estimatedDocumentCount().

Important

Stable API V1 and MongoDB Server Issue

If you are using the Stable API V1 with the "strict" option and a MongoDB Server version between 5.0.0 and 5.0.8 inclusive, method calls to estimatedDocumentCount() might produce an error due to a server bug.

Upgrade to MongoDB Server 5.0.9 or set the Stable API "strict" option to false to avoid this issue.

You can also pass an optional parameter to either of these methods to specify the behavior of the call:

Method
Optional Parameter Class
Description
countDocuments()
CountOptions
You can specify a maximum number of documents to count by using the limit() method or the maximum amount of execution time using the maxTime() method.
estimatedDocumentCount()
EstimatedDocumentCountOptions
You can specify the maximum execution time using the maxTime() method.

Both methods return the number of matching documents as a long primitive.

The following example estimates the number of documents in the movies collection in the sample_mflix database, and then returns an accurate count of the number of documents in the movies collection with Canada in the countries field.

Note

This example connects to an instance of MongoDB using a connection URI. To learn more about connecting to your MongoDB instance, see the connection guide.

// Runs count operations on a collection by using the Java driver
package usage.examples;
import static com.mongodb.client.model.Filters.eq;
import org.bson.Document;
import org.bson.conversions.Bson;
import com.mongodb.MongoException;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class CountDocuments {
public static void main(String[] args) {
// Replace the uri string with your MongoDB deployment's connection string
String uri = "<connection string uri>";
try (MongoClient mongoClient = MongoClients.create(uri)) {
MongoDatabase database = mongoClient.getDatabase("sample_mflix");
MongoCollection<Document> collection = database.getCollection("movies");
Bson query = eq("countries", "Spain");
try {
// Retrieves and prints the estimated number of documents in the collection
long estimatedCount = collection.estimatedDocumentCount();
System.out.println("Estimated number of documents in the movies collection: " + estimatedCount);
// Retrieves and prints the number of documents with a "countries" value of "Spain"
long matchingCount = collection.countDocuments(query);
System.out.println("Number of movies from Spain: " + matchingCount);
// Prints a message if any exceptions occur during the operations
} catch (MongoException me) {
System.err.println("An error occurred: " + me);
}
}
}
}

If you run the preceding sample code, you should see output that looks something like this (exact numbers can vary depending on your data):

Estimated number of documents in the movies collection: 23541
Number of movies from Spain: 755

Tip

Legacy API

If you are using the legacy API, see our FAQ page to learn what changes you need to make to this code example.

For additional information on the classes and methods mentioned on this page, see the following API Documentation:

←  Watch for ChangesRetrieve Distinct Values of a Field →