You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C语言中获取MongoDB查询游标返回的文档数量?

在C语言中获取MongoDB查询结果文档数量的方法

方法一:直接使用计数API(推荐)

MongoDB C Driver(libmongoc)提供了mongoc_collection_count_documents()函数,可直接执行计数查询,效果和Python的cursor.count()一致,无需遍历所有文档,效率更高。

示例代码:

#include <mongoc/mongoc.h>
#include <stdio.h>
#include <inttypes.h>

int main() {
    mongoc_client_t *client;
    mongoc_collection_t *collection;
    bson_error_t error;
    bson_t *query;
    int64_t count;

    // 初始化驱动
    mongoc_init();

    // 创建客户端连接
    client = mongoc_client_new("mongodb://localhost:27017/");
    if (!client) {
        fprintf(stderr, "创建客户端失败\n");
        return 1;
    }

    // 获取目标集合
    collection = mongoc_client_get_collection(client, "你的数据库名", "你的集合名");
    if (!collection) {
        fprintf(stderr, "获取集合失败\n");
        mongoc_client_destroy(client);
        return 1;
    }

    // 构建查询条件(空查询统计所有文档)
    query = bson_new();
    // 如需筛选,例如统计status为active的文档:
    // BSON_APPEND_UTF8(query, "status", "active");

    // 执行计数操作
    count = mongoc_collection_count_documents(
        collection,
        query,
        NULL,  // 可选配置:如skip、limit等
        NULL,  // 读偏好设置
        NULL,  // 会话(可选)
        &error
    );

    if (count < 0) {
        fprintf(stderr, "计数失败: %s\n", error.message);
    } else {
        printf("文档数量: %" PRId64 "\n", count);
    }

    // 释放资源
    bson_destroy(query);
    mongoc_collection_destroy(collection);
    mongoc_client_destroy(client);
    mongoc_cleanup();

    return 0;
}

方法二:遍历游标计数(不推荐,仅适用于已获取游标的场景)

如果已经通过mongoc_collection_find()拿到了游标,只能通过遍历游标逐个计数,结果集较大时效率极低,仅适合小数据量场景:

// 假设已存在有效的mongoc_cursor_t *cursor
int64_t count = 0;
const bson_t *doc;

while (mongoc_cursor_next(cursor, &doc)) {
    count++;
}

// 检查游标是否出错
bson_error_t error;
if (mongoc_cursor_error(cursor, &error)) {
    fprintf(stderr, "游标错误: %s\n", error.message);
} else {
    printf("文档数量: %" PRId64 "\n", count);
}

注意事项

  • 确保使用最新版libmongoc,旧版本的mongoc_collection_count()已被废弃,优先使用mongoc_collection_count_documents()。
  • 可通过mongoc_collection_count_documents()的第三个参数bson_t *opts设置skip、limit,模拟带分页的计数逻辑。

内容的提问来源于stack exchange,提问作者Rishabh Jain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 17:32:09