【发布时间】: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