2012-08-13 6 views
0

node-mongodb-native를 사용하는 map/reduce 방법이 있습니다. 'product_id'에 다른 레코드 만 반환하려고합니다. 이것은 내가 지금까지 가지고있는 것입니다 :MongoDB node-mongodb-native map/reduce

 var map = function() { 
      emit("_id", {"_id" : this._id, 
         "product_id" : this.product_id, 
         "name" : this.name 
         }); 
     } 

     var reduce = function(key, values) { 

      var items = []; 
      var exists; 

      values.forEach(function(value) { 

       if(items.length > 0) { 

        items.forEach(function(item_val, key) { 
         if(item_val.product_id == value.product_id) { 
          exists = true; 
         } 
        }); 

        if(!exists) { 
         items.push(value); 
        } 

        exists = false; 

       } else { 

        items.push(value); 
       } 
      }); 

      return {"items" : items}; 
     } 

     this.collection.mapReduce(map, reduce, {out : {inline: 1}, limit: 4}, function(err, results) { 
      if (err) { 
       console.log(err); 
      } else { 
       console.log(results[0].value.items); 
      } 
     }); 

내 논리가있는 부분이 작동하지 않는 것 같습니다. 그것은 여전히 ​​product_id가 같은 중복 레코드를 추가합니다.

도움이 정말 좋을 것입니다 - 감사합니다! 사실

+0

지도가 우선 잘못이다, 희망은 도움이하는 시도 :'방출 (this.product_id, { "_id"this._id를, "이름": this.name});' – Sammaye

+0

는 건너 뛰기 감소 그리고 finalize에서 출력 문서에서'values' 행의'[0]'만 제거하고 고유 문서를 가지고 있으십시오. – Sammaye

+1

문서 구조가 무엇인지 정확하게 설명하고지도의 최종 결과가 줄어들면 무엇을 기대하는지 이해하면 도움이됩니다. –

답변

2

, 당신이 뭘하려고 무엇의 예 :

var map = function() { 
    emit(this.product_id, {"_id" : this._id, "name" : this.name }); 
} 

var finailise = function(key, value){ 
    return value[0]; // This might need tweaking, ain't done MRs in a while :/ 
} 

그러나 서로 다른 두 가지 유형이 있습니다주의 마십시오

  • 먼저
  • 최근 발견했습니다

구별 할 수있는 표준 방법이 없으며 각 DB에는 자체 메서드가 있습니다. SQL dat 간에는 표준이 아닙니다. 그래서 당신이 당신이 뚜렷하게하고 싶은 방법을 알기까지 당신의 의견이 내려집니다. 위의 것은 첫 번째 별개의 발견입니다. 다음과 같이 뚜렷하게 구별 할 수 있습니다.

var finailise = function(key, value){ 
    return value[value.length-1]; 
} 

또는 이와 비슷한 방식으로 어쨌든 시작해야합니다.

관련 문제