2012-08-13 123 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]; 
} 

或类似的东西,应该让你开始反正。

希望它能帮助,