For AI agents: a documentation index is available at https://www.mongodb.com/docs/llms.txt — markdown versions of all pages are available by appending .md to any URL path.

Count Documents

You can count the number of documents in a collection by calling one of the following methods on a Collection instance:

Each method returns the count as a u64 instance.

Note

If you don't pass a filter to the count_documents() method, MongoDB counts the total number of documents in the collection.

This example counts documents in the restaurants collection of the sample_restaurants database.

The following code first uses the estimated_document_count() method to count the total number of documents in the collection. Then, the example uses the count_documents() method to count the number of documents that match a query filter. The filter matches documents in which the value of the name field includes the string "Sunset":

Select the Asynchronous or Synchronous tab to see the corresponding code for each runtime:

use std::env;use mongodb::{ bson::doc, Client, Collection };use bson::Document; #[tokio::main]async fn main() -> mongodb::error::Result<()> { let uri = "<connection string>"; let client = Client::with_uri_str(uri).await?; let my_coll: Collection<Document> = client .database("sample_restaurants") .collection("restaurants"); let ct = my_coll.estimated_document_count(None).await?; println!("Number of documents: {}", ct); let ct = my_coll.count_documents(doc! { "name": doc! { "$regex": "Sunset" } }, None).await?; println!("Number of matching documents: {}", ct); Ok(())}
Rate this page