我有一个简单的更新脚本,由于某种原因,它会遍历每个文档两次并继续执行代码。我不明白为什么会这样......任何帮助都会非常感激:
db.products.find().forEach(function(product) {
var numerator = {
0 : [],
1 : [],
2 : [],
3 : [],
4 : []
},
denominator= {
0 : [],
1 : [],
2 : [],
3 : [],
4 : []
};
product.reviews.forEach(function(review) {
var weight = review.weight.reputation + review.weight.reviewRelevance,
i = 0;
review.score.forEach(function(score) {
if ( i == 0){
score.rating = Math.ceil((score.rating/100) * 10);
}else {
score.rating = Math.ceil((score.rating/25) * 10);
numerator[i].push(score.rating * weight);
denominator[i].push(weight);
i++;
}
});
var s = 0;
for (var key in product.score) {
var obj = product.score[key];
if ( key == 'Overall'){
obj.percent = obj.rating;
obj.rating = Math.ceil((obj.rating/100) * 10);
}else {
obj.rating = Math.ceil((obj.rating/25) * 10);
}
obj.info = {
'numerator' : array_sum(numerator[s]),
'denominator' : array_sum(denominator[s]),
};
s++;
}
});
db.products.save(product);
});
function array_sum (array) {
var key, sum = 0;
if (array && typeof array === 'object' && array.change_key_case) { // Duck-type check for our own array()-created PHPJS_Array
return array.sum.apply(array, Array.prototype.slice.call(arguments, 0));
}
// input sanitation
if (typeof array !== 'object') {
return null;
}
for (key in array) {
if (!isNaN(parseFloat(array[key]))) {
sum += parseFloat(array[key]);
}
}
return sum;
}
答案 0 :(得分:1)
默认情况下,光标不会处理修改文档时的情况,并将其移动到集合的末尾(将再次读取)。您可以使用快照游标来避免多次读取同一文档的多个版本。
查看文档:{{3}}