Overview
在本指南中,您可以学习;了解如何检索集合中文档数量的准确估计计数。
样本数据
本指南中的示例使用movies sample_mflixAtlas示例数据集的 数据库中的 集合。要学习;了解如何创建免费的MongoDB Atlas 群集并加载示例数据集,请参阅 入门指南。
检索准确的计数
使用 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);
21349
对特定文档进行计数
要返回匹配特定搜索条件的文档计数,请在 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);
10
自定义计数行为
mongoc_collection_count_documents() 函数接受 bson_t 结构形式的可选参数,该结构表示一设立可用于配置计数操作的选项。如果不指定任何选项,驱动程序不会自定义计数操作。
下表描述了可以设置用于自定义countDocuments()的选项:
选项 | 说明 |
|---|---|
| Specifies a comment to attach to the operation. |
| Sets the number of documents to skip before returning results. |
| Sets the maximum number of documents to count. Must be a positive integer. |
| Specifies the kind of language collation to use when sorting
results. For more information, see Collation
in the MongoDB Server manual. |
| Sets the index to scan for documents. |
有关选项的完整列表,请参阅 API文档 的 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);
21349
检索估计计数
使用 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);
21349
自定义估计计数行为
mongoc_collection_estimated_document_count() 函数接受 bson_t 结构形式的可选参数,该结构表示可用于配置计数操作的选项。如果不指定任何选项,驱动程序不会自定义计数操作。
下表描述了可以设置用于自定义mongoc_collection_estimated_document_count()的选项:
选项 | 说明 |
|---|---|
| Specifies a comment to attach to the operation. |
| Specifies the kind of language collation to use when sorting
results. For more information, see Collation
in the MongoDB Server manual. |
有关选项的完整列表,请参阅 API文档 的 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);
21349
API 文档
要学习;了解有关本指南中讨论的任何函数的更多信息,请参阅以下API文档: