MongoDB - how do I include this group () request to display / reduce

I have a collection in which 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 it:

db.keywords_counter.group({key     : {keyword:true}, 
                          cond    : {access_key: "xxxxx"}, 
                          reduce  : function(obj, prev){prev.total += obj.count},
                          initial : {total:0}})

How can I achieve the same with map / reduce? [I start with the map / reduce the beginner and try to circle the concept around me.]

+3
source share
1 answer

Found a 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'}})
+3
source

Source: https://habr.com/ru/post/1767842/


All Articles