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

Loo*_*urr 12 javascript iterator mongodb coffeescript 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
Run Code Online (Sandbox Code Playgroud)

哪些日志

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
Run Code Online (Sandbox Code Playgroud)

然后停下来.但是当我从终端登录mongo并运行时

> db.keys.count()
2317381
Run Code Online (Sandbox Code Playgroud)

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

Joh*_*one 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();
          });
        };
      });
Run Code Online (Sandbox Code Playgroud)