【问题标题】:mongocxx count documents in collectionmongocxx 统计集合中的文档
【发布时间】:2020-09-18 10:28:30
【问题描述】:

在 shell 中计算集合中的文档数量既简单又快速(显然是恒定时间)。

> db.my_collection.count()
12345678
>

在 C++ 中我试试这个:

mongocxx::client client;
mongocxx::database db = MongoInit(client, ...);
vector<string> collection_names;
mongocxx::cursor cursor = db.list_collections();
for (const bsoncxx::document::view& doc : cursor) {
    string collection_name = doc["name"].get_utf8().value.to_string();
    collection_names.push_back(collection_name);
}

bsoncxx::document::view empty_filter;
for (const string& collection_name : collection_names) {
    LOG_INFO << collection_name;
    mongocxx::collection collection = db[collection_name];
    int64_t collection_count = collection.count_documents(empty_filter);
    LOG_INFO << collection_name << "    " << collection_count;
}

这段代码可以工作,但速度很慢。我是不是做错了什么?

【问题讨论】:

    标签: c++ mongodb c++14 mongo-cxx-driver mongo-c-driver


    【解决方案1】:

    countcount_documents 是非常不同的功能。

    MongoDB 维护有关每个集合的元数据,其中包含存储的文档数量。此数字在插入文档时递增,在删除文档时递减。此数字可能与集合不同步,因此应将其视为近似值。

    count 只是从元数据中读取该数字并将其返回,使其在恒定时间内完成。

    count_documents 函数扫描集合以获取准确的文档计数,而不是从元数据中获取近似计数。

    如果您需要快速而不是精确的结果,请使用estimated_document_count 函数。

    【讨论】:

      猜你喜欢
      • 2019-01-21
      • 1970-01-01
      • 2021-05-14
      • 2023-02-07
      • 2019-05-23
      • 2018-06-10
      • 1970-01-01
      • 1970-01-01
      • 2021-04-24
      相关资源
      最近更新 更多