Counting the number of documents in a collection is easy and fast (apparently constant time) in the shell.
> db.my_collection.count()
12345678
>
In C++ I try this:
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;
}
This code works but is strangely slow. Have I done something wrong?