You can count the number of documents in a collection by calling one of
the following methods on a Collection instance:
count_documents(): counts the number of documents that match a query filter. To learn more about creating query filters, see the Specify a Query guide.
estimated_document_count(): estimates the total number of documents in a collection by using collection metadata.
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.
Example
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; 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(()) }
// Your values might differ Number of documents: 25216 Number of matching documents: 10
use std::env; use mongodb::{ bson::{ Document, doc }, sync::{ Client, Collection } }; fn main() -> mongodb::error::Result<()> { let uri = "<connection string>"; let client = Client::with_uri_str(uri)?; let my_coll: Collection<Document> = client .database("sample_restaurants") .collection("restaurants"); let ct = my_coll.estimated_document_count(None)?; println!("Number of documents: {}", ct); let ct = my_coll.count_documents(doc! { "name": doc! { "$regex": "Sunset" } }, None)?; println!("Number of matching documents: {}", ct); Ok(()) }
// Your values might differ Number of documents: 25216 Number of matching documents: 10