2012-08-13 170 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 2012-08-13 20:25:28

+0

跳過減少並且只是在finalize中從輸出的文檔中除去'values'行的所有'[0]',並且你有獨特的文檔。 – Sammaye 2012-08-13 20:26:42

+1

如果您準確地解釋了文檔的結構和您期望從地圖最終獲得的結果得到的結果會有所幫助,那將會很有幫助。 – 2012-08-14 01:56:33

回答

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 :/ 
} 

請注意但有兩種截然不同的:

  • 首先找到
  • 最後找到

有沒有標準的方法來區分,每個數據庫有它自己的方法,它甚至不跨SQL數據標準降低,這是由你來知道你想要區分的方式。上面的第一個發現不同。你可以做一個最後發現截然不同,如:

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

或類似的東西,應該讓你開始反正。

希望它能幫助,