Docs Menu
Docs Home
/ / /
Kotlin Coroutine
/

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 an accurate count of 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:

val options = CountOptions().hintString("_id_")
val numDocuments = collection.countDocuments(BsonDocument(), options)

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() may 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 Spain in the countries field. If you run the preceding sample code, you should see output that looks something like this (exact numbers may vary depending on your data):

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.

import com.mongodb.MongoException
import com.mongodb.client.model.Filters
import com.mongodb.kotlin.client.coroutine.MongoClient
import kotlinx.coroutines.runBlocking
data class Movie(val countries: List<String>)
fun main() = runBlocking {
// Replace the uri string with your MongoDB deployment's connection string
val uri = "<connection string uri>"
val mongoClient = MongoClient.create(uri)
val database = mongoClient.getDatabase("sample_mflix")
val collection = database.getCollection<Movie>("movies")
val query = Filters.eq(Movie::countries.name, "Spain")
try {
val estimatedCount = collection.estimatedDocumentCount()
println("Estimated number of documents in the movies collection: $estimatedCount")
val matchingCount = collection.countDocuments(query)
println("Number of movies from Spain: $matchingCount")
} catch (e: MongoException) {
System.err.println("An error occurred: $e")
}
mongoClient.close()
}
Estimated number of documents in the movies collection: 23541
Number of movies from Spain: 755

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

Back

Watch for Changes