MongoDB Cursor - 计算和枚举文档的有效方法(在Node中)

时间:2015-05-29 12:57:33

标签: node.js mongodb

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

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

但是这两个命令会运行两次查询,这可能效率不高?

在不运行查询两次的情况下,确定我将迭代的文档数量的最有效方法是什么?我的文档很大。

MongoDB'是否知道'在开始通过游标返回文档之前将返回多少个文档?我可以在哪里阅读有关此信息的Mongo内部信息?

我在节点内运行它,并且我使用标准的MongoDB节点驱动程序。因此,解决方案需要处理通常的节点回调机制等等。

由于

修改

我已将原始问题修改为使用节点驱动程序

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
     });
}

1 个答案:

答案 0 :(得分:3)

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

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

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