我有一个集合,每个文档都是这样的
{access_key:'xxxxxxxxx', keyword: "banana", count:12, request_hour:"Thu Sep 30 2010 12:00:00 GMT+0000 (UTC)"}
{access_key:'yyyyyyyyy', keyword: "apple", count:25, request_hour:"Thu Sep 30 2010 12:00:00 GMT+0000 (UTC)", }
.....
实现这一目标:
SELECT keyword, sum(count) FROM keywords_counter WHERE access_key = 'xxxxxxxxx' GROUP BY keyword
我这样做:
db.keywords_counter.group({key : {keyword:true},
cond : {access_key: "xxxxx"},
reduce : function(obj, prev){prev.total += obj.count},
initial : {total:0}})
如何使用map / reduce实现相同的功能? [我是一张地图/缩小初学者并尝试围绕这个概念。]
答案 0 :(得分:4)
找到解决方案:
map = function(){ emit(this.keyword, {count: this.count}); }
reduce = function(key, values){
var total = 0;
for (var i=0; i < values.length, i++) { total += values[i].count; }
return {count: total};
}
db.keywords_counter.mapReduce(map, reduce, {query:{access_key: 'xxxxxxxxx'}})