如何统计mongocxx中collection.find(filter)返回的文档数?cursor无count()方法
统计mongocxx Cursor返回的文档数量
因为mongocxx的cursor本身没有提供count()方法,你可以通过以下两种方式实现统计:
方式一:遍历Cursor手动计数
直接迭代cursor中的每个文档,累加计数。这种方法适合你已经需要处理cursor内的文档,顺便统计数量的场景:
bsoncxx::document::value filter = make_document(...some document...); auto cursor {coll.find(filter.view())}; size_t doc_count = 0; for ([[maybe_unused]] auto&& doc : cursor) { ++doc_count; } // doc_count 即为返回的文档总数
方式二:使用Collection的count_documents方法(推荐)
如果只是需要统计符合过滤条件的文档数量,不需要获取具体文档,直接调用集合的count_documents()方法更高效——这个操作是在数据库端完成统计,无需将所有文档传输到客户端:
bsoncxx::document::value filter = make_document(...some document...); auto doc_count = coll.count_documents(filter.view());
内容的提问来源于stack exchange,提问作者user22343737
相关产品推荐
相关产品推荐

