Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.]

like image 512
rubayeet Avatar asked Jan 28 '26 06:01

rubayeet


1 Answers

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'}})
like image 199
rubayeet Avatar answered Jan 29 '26 19:01

rubayeet