mongodb mapreduce, 实现 select sum(a*b) from test
迷茫
迷茫 2017-05-02 09:18:23
0
2
611

首先介绍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实现,或者用其他方法实现也可以
???????????????????

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(2)
曾经蜡笔没有小新

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"}}}
]);
Ty80

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!