12

我正在使用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

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

4

2 回答 2

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();
          });
        };
      });
于 2014-06-14T16:43:50.613 回答
3

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

对于大多数查询,第一批返回 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) 
    });
});
于 2014-06-14T10:09:31.280 回答