对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

计算文档

在本指南中,您可以学习;了解如何检索集合中文档数量的准确估计计数。

本指南中的示例使用来自 Atlas 示例数据集sample_mflix 数据库中的 movies 集合。要学习如何创建免费的MongoDB Atlas 集群并加载示例数据集,请参阅MongoDB 入门指南

使用 mongoc_collection_count_documents() 函数计算集合中的文档数量。 要计算与指定搜索条件匹配的文档数量,请将查询过滤传递给 mongoc_collection_count_documents() 函数。

要学习;了解有关指定查询的更多信息,请参阅指定查询。

要返回集合中所有文档的计数,请使用空查询过滤调用 mongoc_collection_count_documents() 函数,如以下示例所示:

bson_error_t error;
bson_t *empty_query = bson_new();
int64_t count =
mongoc_collection_count_documents(collection, empty_query, NULL, NULL, NULL, &error);
printf("%" PRId64 "\n", count);
bson_destroy(empty_query);

要返回匹配特定搜索条件的文档计数,请在 mongoc_collection_count_documents() 函数中指定您的查询。 以下示例将打印 movies集合中 year字段值等于 1930 的所有文档的计数:

bson_error_t error;
bson_t *query = BCON_NEW("year", BCON_INT32(1930));
int64_t count =
mongoc_collection_count_documents(collection, query, NULL, NULL, NULL, &error);
printf("%" PRId64 "\n", count);
bson_destroy(query);

mongoc_collection_count_documents() 函数接受 bson_t 结构形式的可选参数,该结构表示一设立可用于配置计数操作的选项。如果不指定任何选项,驱动程序不会自定义计数操作。

下表描述了可以设置用于自定义countDocuments()的选项:

选项
说明

comment

指定要附加到操作的注释。

skip

设置返回结果之前要跳过的文档数。

limit

设置要计数的最大文档数。 必须为正整数。

collation

Specifies the kind of language collation to use when sorting results. For more information, see Collation in the MongoDB Server manual.

hint

设置扫描文档的索引。

For a complete list of options, see the API Documentation for mongoc_collection_count_documents().

以下示例使用 bson_t 结构为 mongoc_collection_count_documents() 操作添加注释:

bson_error_t error;
bson_t *opts = BCON_NEW("comment", BCON_UTF8("Retrieving count"));
int64_t count =
mongoc_collection_count_documents(collection, bson_new(), opts, NULL, NULL, &error);
printf("%" PRId64 "\n", count);
bson_destroy(opts);

使用 mongoc_collection_estimated_document_count() 函数检索集合中文档数量的估计值。 该函数根据集合元数据估计文档的数量,这可能比执行精确计数更快。

以下示例打印集合中的估计文档数:

bson_error_t error;
int64_t count =
mongoc_collection_estimated_document_count(collection, NULL, NULL, NULL, &error);
printf("%" PRId64 "\n", count);

mongoc_collection_estimated_document_count() 函数接受 bson_t 结构形式的可选参数,该结构表示可用于配置计数操作的选项。如果不指定任何选项,驱动程序不会自定义计数操作。

下表描述了可以设置用于自定义mongoc_collection_estimated_document_count()的选项:

选项
说明

comment

指定要附加到操作的注释。

collation

Specifies the kind of language collation to use when sorting results. For more information, see Collation in the MongoDB Server manual.

For a complete list of options, see the API Documentation for mongoc_collection_estimated_document_count().

以下示例使用 bson_t 结构为 mongoc_collection_estimated_document_count() 操作添加注释:

bson_error_t error;
bson_t *opts = BCON_NEW("comment", BCON_UTF8("Retrieving count"));
int64_t count =
mongoc_collection_estimated_document_count(collection, opts, NULL, NULL, &error);
printf("%" PRId64 "\n", count);
bson_destroy(opts);

要学习;了解有关本指南中讨论的任何函数的更多信息,请参阅以下API文档: