计数文档
您可以通过在集合实例上调用以下方法之一来计数集合中的文档数量:Collection
实例
count_documents():统计匹配查询过滤器的文档数量。要了解更多关于创建查询过滤器,请参阅指定查询指南。
estimated_document_count():通过使用集合元数据来估计集合中的总文档数。
每个方法都返回一个 u64
实例的计数。
注意
如果您没有向 count_documents()
方法传递过滤器,MongoDB 将统计集合中的总文档数。
示例
此示例统计了 sample_restaurants
数据库中 restaurants
集合中的文档。
以下代码首先使用 estimated_document_count()
方法统计集合中的总文档数。然后,示例使用 count_documents()
方法统计匹配查询过滤器的文档数。该过滤器匹配 name
字段值为 "Sunset" 的文档
选择异步 或 同步 标签以查看每个运行时的对应代码
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().await?; println!("Number of documents: {}", ct); let ct = my_coll.count_documents(doc! { "name": doc! { "$regex": "Sunset" } }).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().run()?; println!("Number of documents: {}", ct); let ct = my_coll .count_documents(doc! { "name": doc! { "$regex": "Sunset" } }) .run()?; println!("Number of matching documents: {}", ct); Ok(()) }
// Your values might differ Number of documents: 25216 Number of matching documents: 10