Mongo C++ 驱动程序提供了一个函数来获取带有给定查询结果的游标,例如获取 mycol
中字段 x
设置为 1 的所有文档> mydb
数据库的集合我们可以使用以下内容(假设 c
是指向正确配置的 DBClientBase
对象的指针):
auto_ptr<DBClientCursor> cursor = c->query("mydb.mycol", BSON(x << 1));
此外,还有一个函数可以获取给定查询的结果数:
int n = c->count("mydb.mycol", BSON(x << 1));
在开始处理查询结果之前,我需要知道结果的数量。我知道的方法是按以下方式组合这两个操作:
int n = c->count("mydb.mycol", BSON(x << 1));
// Do some checking based on n
...
auto_ptr<DBClientCursor> cursor = c->query("mydb.mycol", BSON(x << 1));
// Process cursor results
...
但是,这涉及 2 个 MongoDB 级别的操作。是否可以在查看结果之前知道游标提供的结果数,以便我可以节省调用 count()
函数?像这样:
auto_ptr<DBClientCursor> cursor = c->query("mydb.mycol", BSON(x << 1));
int n = (get the number from the 'cursor' variable in some way)
// Do some checking based on n
...
// Process cursor results
...
最佳答案
我似乎迟到了,但 cursor.size() 似乎完全符合您的要求。
https://docs.mongodb.com/manual/reference/method/cursor.size/#cursor.size
关于c++ - MongoDB中不使用count()函数,通过游标获取给定查询的结果数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32606775/