计数文档
概述
在本指南中,您可以学习如何使用C++驱动程序来检索集合中文档的确切数量和估计数量。count_documents()
方法返回与查询过滤器匹配的或存在于集合中的文档的确切数量,而estimated_document_count()
方法返回集合中文档的估计数量。
示例数据
本指南中的示例使用来自Atlas示例数据集的sample_training
数据库中的companies
集合。要从您的C++应用程序访问此集合,实例化一个连接到Atlas集群的mongocxx::client
,并将以下值分配给您的db
和collection
变量要了解如何创建免费的MongoDB Atlas集群并加载示例数据集,请参阅Atlas入门指南。
auto db = client["sample_training"]; auto collection = db["companies"];
获取有关指定查询的更多信息,请参阅
获取准确计数
使用count_documents()
方法来统计集合中文档的数量。要统计与特定搜索条件匹配的文档数量,请将查询过滤器文档传递给count_documents()
方法。
获取有关指定查询的更多信息,请参阅指定查询指南。
计算所有文档的数量
要返回集合中所有文档的数量,将一个空过滤器文档传递给count_documents()
方法,如下面的示例所示
auto result = collection.count_documents({}); std::cout << "Number of documents: " << result << std::endl;
Number of documents: 9500
计算特定文档的数量
要返回符合特定搜索条件的文档的数量,将查询过滤器文档传递给count_documents()
方法。
以下示例计算具有founded_year
值为2010
的文档数量
auto result = collection.count_documents(make_document(kvp("founded_year", 2010))); std::cout << "Number of companies founded in 2010: " << result << std::endl;
Number of companies founded in 2010: 33
自定义计数行为
您可以通过传递mongocxx::options::count
类的实例作为参数来修改count_documents()
方法的行为。以下表格描述了您可以在mongocxx::options::count
实例中设置的字段
字段 | 描述 |
---|---|
| 用于操作的排序规则。 类型: bsoncxx::document::view_or_value |
| 用于操作的索引。 类型: mongocxx::hint |
| 附加到操作上的注释。 类型: bsoncxx::types::bson_value::view_or_value |
| 要计数的最大文档数。此值必须为正整数。 类型: std::int64_t |
| 操作可以运行的最大时间(以毫秒为单位)。 类型: std::chrono::milliseconds |
| 在计数文档之前要跳过的文档数。 类型: std::int64_t |
| 用于操作的读取偏好。 类型: mongocxx::read_preference |
以下示例使用count_documents()
方法来计算具有值为50
的number_of_employees
字段的文档数量,并指示操作最多计数100
个结果
mongocxx::options::count opts; opts.limit(100); auto result = collection.count_documents(make_document(kvp("number_of_employees", 50)), opts); std::cout << "Number of companies with 50 employees: " << result << std::endl;
Number of companies with 50 employees: 100
检索估计计数
您可以通过调用estimated_document_count()
方法来检索集合中文档数量的估计值。该方法基于集合元数据估计文档数量,可能比执行精确计数更快。
以下示例估计集合中的文档数量
auto result = collection.estimated_document_count(); std::cout << "Estimated number of documents: " << result << std::endl;
Estimated number of documents: 9500
自定义估计计数行为
您可以通过将mongocxx::options::estimated_document_count
类的实例作为参数传递来修改estimated_document_count()
方法的行为。以下表格描述了您可以在mongocxx::options::estimated_document_count
实例中设置的字段
字段 | 描述 |
---|---|
| 操作可以运行的最大时间(以毫秒为单位)。 类型: std::chrono::milliseconds |
| 附加到操作上的注释。 类型: bsoncxx::types::bson_value::view_or_value |
| 用于操作的读取偏好。 类型: mongocxx::read_preference |
以下示例使用 estimated_document_count()
方法返回集合中文档数量的估计值,并指导操作在最多 1000
毫秒内运行
mongocxx::options::estimated_document_count opts; opts.max_time(std::chrono::milliseconds{1000}); auto result = collection.estimated_document_count(opts); std::cout << "Estimated number of documents: " << result << std::endl;
Estimated number of documents: 9500
API 文档
要了解更多关于本指南中讨论的任何方法或类型的信息,请参阅以下 API 文档