开发者

MongoDB - how I turn this group() query to map/reduce

开发者 https://www.devze.com 2023-01-18 11:19 出处:网络
I have a collection where each document looks like this {access_key:\'xxxxxxxxx\', keyword: \"banana\", count:12, request_hour:\"Thu Sep 30 2010 12:00:00 GMT+0000 (UTC)\"}

I have a collection where each document looks like this

{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)", }
.....

To achieve this:

SELECT keyword, sum(count) FROM keywords_counter WHERE access_key = 'xxxxxxxxx' GROUP BY keyword

I'm doing this:

db.keywords_counter.group({key     : {开发者_如何转开发keyword:true}, 
                          cond    : {access_key: "xxxxx"}, 
                          reduce  : function(obj, prev){prev.total += obj.count},
                          initial : {total:0}})

How do I achieve the same thing with map/reduce? [I'm a map/reduce beginner and trying to wrap my head around the concept.]


Found the solution:

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'}})
0

精彩评论

暂无评论...
验证码 换一张
取 消