【问题标题】:How do I iterate over an entire MongoDB collection using mongojs?如何使用 mongojs 遍历整个 MongoDB 集合?
【发布时间】:2014-08-04 14:03:35
【问题描述】:

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

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

【问题讨论】:

    标签: javascript mongodb coffeescript iterator mongojs


    【解决方案1】:

    您需要使用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();
              });
            };
          });
    

    【讨论】:

      【解决方案2】:

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

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

      您可以尝试使用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) 
          });
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-08
        • 2020-11-20
        • 2018-08-07
        • 2019-12-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多