MongoDB游标 – 计算和枚举文档的有效方法(在节点中)

我想知道在迭代游标之前有多less文档将由我的MongoDB游标处理。 我是否必须运行查询两次,还是可以确定游标的大小,然后遍历游标而不运行查询两次?

myCount = myCollection.find({complex query}).count(); // will get my count myCursor = myCollection.find({complex query}); // will get my cursor for iteration 

但是这两个命令会运行查询两次,这可能是低效的?

什么是最有效的方式来确定我将遍历的文档的数量而不运行查询两次? 我的文档相当大。

MongoDB是否知道在开始通过光标返回之前将返回多less个文档? 我在哪里可以阅读Mongo内部的这个信息?

我在节点中运行这个,我使用标准的MongoDB节点驱动程序。 所以,解决scheme需要处理通常的节点callback机制等。

谢谢

编辑

我已经修改了原来的问题,说明我正在使用节点驱动程序

EDIT2

yogesh的答案是正确的,我只需要找出节点的语法。 我已经显示了下面的工作代码以防万一

 db.collection('collectionName', function(err, collection) { function processItem(err, item) { if (item === null) { db.close(); callback(null, {info: "yippee"}); return; } cursor.nextObject(processItem); // continue looping } var cursor = collection.find({foo:1}); cursor.count(function(err,count){ console.log('resultCursor size='+count); cursor.nextObject(processItem); // Start of the loop }); } 

检查cursor.next,查找db.collection.find()方法返回的游标中的下一个文档 。 所以你的情况你应该写作(在mongo shell上testing)

 var collectionData = myCollection.find({complex query}) collectionData.count() // return matching documents count collectionData.next() // return next documents 

或者你也检查mongo hasnext ,如果db.collection.find()查询返回的游标可以进一步迭代返回更多的文档,则返回true。