search

Home  >  Q&A  >  body text

mongodb mapreduce, 实现 select sum(a*b) from test

首先介绍user collection

user {'username':, 'age':, 'account':}

下面是正常的group_by 和count实现

//SQL实现

select username,count(sku) from user group by username

//MapReduce实现

map=function (){
    emit(this.username,{count:1})
}

reduce=function (key,values){
    var cnt=0;   
    values.forEach(function(val){ cnt+=val.count;});  
    return {"count":cnt}
}

//执行mapreduce

db.test.mapReduce(map,reduce,{out:"mr1"})

db.mr1.find()

{ "_id" : "Joe", "value" : { "count" : 416 } }
{ "_id" : "Josh", "value" : { "count" : 287 } }
{ "_id" : "Ken", "value" : { "count" : 297 } }

然后

//SQL实现

select sum(age * account) from user

//MapReduce实现,或者用其他方法实现也可以
???????????????????

迷茫迷茫2812 days ago658

reply all(2)I'll reply

  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-02 09:20:23

    Usually we recommend avoiding using map/reduce in MongoDB, as the performance is not very ideal. Most of the time it can be replaced by the aggregation framework, especially when only one table is involved.

    db.user.aggregate([
      {$group: {_id: '$username', count: {$sum: 1}}}
    ]);

    Please check the syntax of aggregation for specific syntax. a*bIt will be a little more complicated. What you actually need is the value of a*b of each record (pipline1), and then sum it up (pipline2):

    db.user.aggregate([
      {$group: {_id: "$username", temp_result: {$multiply: ["$age", "$account"]}}},
      {$group: {_id: null, result: {$sum: "$temp_result"}}}
    ]);

    reply
    0
  • PHP中文网

    PHP中文网2017-05-02 09:20:23

    var map = function(){

    emit("sum",this.age*this.account);
    }

    var reduce = function(key,values){

    var cnt = 0;
    values.forEach(function(val){cnt+=val;});
    return {"sumAll":cnt};
    }

    After the above definition is completed, execute: db.user.mapReduce(map,reduce,{out:"mr1"});
    Then query the document of mr1: db.mr1.find();
    The result will be obtained

    reply
    0
  • Cancelreply