【问题标题】:MongoDB - how I turn this group() query to map/reduceMongoDB - 我如何将此 group() 查询转换为 map/reduce
【发布时间】:2010-10-04 09:34:49
【问题描述】:

我有一个集合,每个文档看起来像这样

{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 实现相同的目标? [我是一个 map/reduce 初学者,并试图围绕这个概念来思考。]

【问题讨论】:

    标签: mongodb mapreduce


    【解决方案1】:

    找到解决方案:

    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。
    • @thetuxracer - 检查要发出的第二个参数是否与 reduce 返回的对象相同。它对我有用。
    • 我明白了,我错误地添加了计数,我没有使用值数组。但是您的评论帮助我澄清了另一个问题:D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多