我有一个包含50万个文档的馆藏(馆藏大约需要
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次?

最佳答案

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

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

09-11 19:46
查看更多