【问题标题】:Iterating cursor on big collection in mongo and node doesn't return all results?在mongo和node的大集合上迭代游标不返回所有结果?
【发布时间】:2017-02-27 15:09:00
【问题描述】:

我有一个包含 500k 文档的集合(集合大约需要 130mb)

我正在使用标准的 mongodb 驱动程序:

var mongodb = require('mongodb');

我正在尝试使用游标在 node.js 中遍历此集合。 (因为 .toArray 需要很长时间才能将整个数据集放入内存)

var cursor = db.collection('test').find({});

cursor.each(function(err, doc) {
   // only does this 1000 times
});

我发现它只做了 1000 次,所以我查看了文档 https://mongodb.github.io/node-mongodb-native/api-generated/cursor.html 并在“每个”部分下,它说要增加批量大小。

所以我做了一个非常大的批量,我没有找到让它无限的方法。如果您知道方法,请告诉我。

var cursor = db.collection('test').find({}).batchSize(1000000000000);
cursor.each(function(err, doc) {
    // only does this 30382 times
});

再增加批量大小不会使其迭代更多的元素,然后是 30382。

如何让cursor.each() 迭代 500,000 次?

【问题讨论】:

    标签: javascript node.js mongodb


    【解决方案1】:

    您可以跟踪索引,如果出现错误,您可以再次从离开的地方继续:

    const iterateCollection = (skip) => {
     const cursor = db.collection('test').find({}).skip(skip);
       cursor.each(function(err, doc) {
       skip++;
       if(err){
         //if err due to overflow
         iterateCollection (skip)
       }
     });
    };
    
    iterateCollection(0);
    

    【讨论】:

      【解决方案2】:

      我设法使用“forEach”而不是“each”来解决这个问题......我不知道有什么区别,我只知道它到目前为止有效。所以

      var cursor = db.collection('test').find();
      
      cursor.forEach(function(doc) {
         // do stuff, does it 500,000 times for my collection...
      
      }, function(err) {
          // finished
        db.close();
      });
      

      现在唯一的问题是 forEach 像 1 月的糖蜜一样慢,所以有兴趣听听其他解决方案。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-02-15
        • 1970-01-01
        • 2017-07-19
        • 2013-05-16
        • 1970-01-01
        • 2012-05-15
        • 2017-01-12
        • 1970-01-01
        相关资源
        最近更新 更多