0

我有一个简单的更新脚本,由于某种原因,它会遍历每个文档两次并继续执行代码。我不明白为什么会这样......任何帮助将不胜感激:

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;
}
4

1 回答 1

1

默认情况下,当您修改文档并将其移动到集合的末尾(它将被再次读取)时,光标不会处理这种情况。在这种情况下,您可以使用快照游标来避免多次读取同一文档的多个版本。

检查文档:docs.mongodb.org/manual/reference/operator/snapshot

于 2013-02-09T22:04:45.143 回答