如何使用mongojs迭代整个MongoDB集合?

时间:2014-06-13 23:20:06

标签: javascript mongodb coffeescript iterator mongojs

我正在使用mongojs而我正在尝试迭代集合中的所有元素

index = 0

db.keys.find({}, {uid: 1, _id: 0}).forEach((err, key) =>
    if err?
        console.log err
    else 
        console.log (++index) + " key: " + key_uid

记录

1 key: bB0KN
2 key: LOtOL
3 key: 51xJM
4 key: x9wFP
5 key: hcJKP
6 key: QZxnE
.
.
.
96 key: EeW6E
97 key: wqfmM
98 key: LIGHK
99 key: bjWTI
100 key: 2zNGE
101 key: F71mL

然后停止。但是当我从终端登录mongo并运行

> db.keys.count()
2317381

很明显它应该返回更多的键。您有什么想法会导致这种行为吗?

2 个答案:

答案 0 :(得分:11)

您需要使用each()方法,而不是forEach()。 forEach()将遍历批处理中的每个文档 - 正如您所发现的那样默认为101. each()将遍历游标中的每个文档。来自文档:

  

<强>每个

     

迭代此游标的所有文档。和。一样   {cursor.toArray},如果这样的话,并不会迭代所有元素   光标已被预先访问过。在那种情况下,{cursor.rewind}可以   用于重置光标。但是,与{cursor.toArray}不同,   在任何给定的游标中,游标只能容纳最大批量大小的元素   指定批量大小的时间。否则,呼叫者负责   确保整个结果符合记忆。

http://mongodb.github.io/node-mongodb-native/api-generated/cursor.html

示例代码:

// Grab a cursor
      var cursor = collection.find();

      // Execute the each command, triggers for each document
      cursor.each(function(err, item) {

        // If the item is null then the cursor is exhausted/empty and closed
        if(item == null) {

          // Show that the cursor is closed
          cursor.toArray(function(err, items) {
            assert.ok(err != null);

            // Let's close the db
            db.close();
          });
        };
      });

答案 1 :(得分:3)

您只看到前101个文档,因为它是MongoDB驱动程序在第一个batch中从服务器获取的默认文档数。

  

对于大多数查询,第一批返回101个文档或刚刚足够   文件超过1兆字节。后续批量大小为4兆字节。

您可以尝试使用find,然后迭代文档。

coll.find({}, {uid:1, _id : 0}, function(err, docs){
    if (err) {
        console.log(err);
        return;
    }
    docs.forEach(function(doc, index) { 
        console.log(index + " key: " + doc.uid) 
    });
});