0
我有一個簡單的更新腳本,出於某種原因遍歷每個文檔兩次並繼續執行代碼。我不明白爲什麼會這樣...任何幫助將不勝感激:Mongo更新腳本
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;
}
試試這個:http://docs.mongodb.org/manual/reference/operator/snapshot/,(這並不意味着不存在在你的代碼沒有錯誤),但在某些情況下可以解決您的問題。 – attish 2013-02-09 12:15:58
感謝一羣工作,添加一個答案,所以我可以接受它 – Jacinto 2013-02-09 21:37:22