2013-02-09 1 views
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; 
} 
+0

이 시도 경우에 따라 문제를 해결할 수 있습니다. – attish

+0

감사합니다. 효과가있는 묶음으로 답변을 추가하여 허용 할 수 있습니다. – Jacinto

답변

1

는 커서가없는 상황을 처리 않습니다 다시 읽게됩니다.) 동일한 문서의 여러 버전을 여러 번 읽지 않으려면이 경우 스냅 샷 커서를 ​​사용할 수 있습니다.

확인 문서 (이 코드에서 오류가 없다는 것을 의미하지 않는다) http://docs.mongodb.org/manual/reference/operator/snapshot/,하지만 : docs.mongodb.org/manual/reference/operator/snapshot