Docs 菜单
Docs 主页
/ / /
Rust 驱动程序
/

计算文档

您可以通过在 Collection实例上调用以下方法之一来计算collection中的文档数量:

  • count_documents() :计算与查询过滤匹配的文档数量。要学习;了解有关创建查询筛选器的更多信息,请参阅《 指定查询》指南。

  • estimated_document_count() :使用集合元数据估计集合中的文档总数。

每个方法都会以u64实例的形式返回该计数。

注意

如果没有向count_documents()方法传递筛选器,MongoDB 将计算collection中的文档总数。

此示例对 sample_restaurants数据库的 restaurants集合中的文档进行计数。 该示例使用 estimated_document_count() 方法计算集合中的文档总数。 然后,该示例使用 count_documents() 方法计算 name字段的值包含字符串 "Sunset" 的文档数量。

您可以将 restaurants集合中的文档作为 Document 类型或自定义数据类型的实例访问权限。 要指定哪种数据类型表示集合的数据,请将突出显示的行上的 <T> 类型参数替换为以下值之一:

  • <Document>:将集合文档表示为BSON文档

  • <Restaurant>:将集合文档表示为 Restaurant 结构的实例,该结构在代码顶部定义

选择 AsynchronousSynchronous标签页,查看每个运行时的相应代码:

use std::env;
use mongodb::{
bson::{ doc, Document },
Client,
Collection
};
use serde::{ Deserialize, Serialize };
#[derive(Serialize, Deserialize, Debug)]
struct Restaurant {
name: String,
cuisine: String,
}
#[tokio::main]
async fn main() -> mongodb::error::Result<()> {
let uri = "<connection string>";
let client = Client::with_uri_str(uri).await?;
// Replace <T> with the <Document> or <Restaurant> type parameter
let my_coll: Collection<T> = 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 }
};
use serde::{ Deserialize, Serialize };
#[derive(Serialize, Deserialize, Debug)]
struct Restaurant {
name: String,
cuisine: String,
}
fn main() -> mongodb::error::Result<()> {
let uri = "<connection string>";
let client = Client::with_uri_str(uri)?;
// Replace <T> with the <Document> or <Restaurant> type parameter
let my_coll: Collection<T> = 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

后退

删除多个