user {'username':, 'age':, 'account':}
//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实现,或者用其他方法实现也可以
???????????????????
曾经蜡笔没有小新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*b
It 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"}}}
]);
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