为什么这个MongoDB循环执行的次数比预期的多?

时间:2014-04-29 05:35:46

标签: javascript mongodb

我有这个服务器端的JS脚本:

// Run processNames on all rows in cities
var cur = db.cities.find();
cur.immortal = true;
var j = 0;
var total = cur.count();
cur.forEach(function(obj) {
    processNames(obj);
    if (j % 100000 === 0) {
        print(j + "/" + total + " cities processed");
    }
    j++;
});
print("Completed load: " + j + " cities processed");

在输出中,我看到了:

...
4800000/3411205 cities processed
4900000/3411205 cities processed
5000000/3411205 cities processed
5100000/3411205 cities processed
5200000/3411205 cities processed
5300000/3411205 cities processed
5400000/3411205 cities processed
5500000/3411205 cities processed

怎么会发生这种情况?游标仅返回3411205文档,但forEach循环执行超过500万次。发生了什么事?

1 个答案:

答案 0 :(得分:1)

我认为您在processNames()方法中修改文档会导致MongoDB重定位文档。您可以使用snapshot()来解决此问题。

var cur = db.cities.find().snapshot();