javascript - 如何使用 mongojs 遍历整个 MongoDB 集合?

标签 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

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

最佳答案

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

each

Iterates over all the documents for this cursor. As with {cursor.toArray}, not all of the elements will be iterated if this cursor had been previouly accessed. In that case, {cursor.rewind} can be used to reset the cursor. However, unlike {cursor.toArray}, the cursor will only hold a maximum of batch size elements at any given time if batch size is specified. Otherwise, the caller is responsible for making sure that the entire result can fit the memory.

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

关于javascript - 如何使用 mongojs 遍历整个 MongoDB 集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24215021/

相关文章:

javascript - 如何使用 HTML5 和 CSS 更改按钮背景颜色 3 次

c# - MongoDB 获取服务器

css - 破折号:数字小部件背景颜色

javascript - 从 Marionette 中的父级扩展 Coffeescript 子类函数

javascript - 如何在 React js 中设置响应式样式以响应模态?

javascript - JSON解析错误

javascript - 如何使用 JavaScript 记录人们在文本框中键入的内容?

php - MongoDB,在集合之间使用 Mongodb ObjectID

mongodb - Golang/mgo : How can I store ISODate by GMT+8 Time Zone in mongodb?

javascript - 从对象返回唯一键列表的正确方法