First, introduce user collection.
user {'username':, 'age':, 'account':}
The following are normal group_by and count implementations
//SQL implementation
select username,count(sku) from user group by username
//MapReduce Implementation
map=function (){
emit(this.username,{count:1})
}
reduce=function (key,values){
var cnt=0;
values.forEach(function(val){ cnt+=val.count; });
return {"count":cnt}
}
//Execute 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 } }
Then
//SQL implementation
select sum(age * account) from user
//MapReduce implementation, or other methods can also be used
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
In general, we would suggest avoiding using map/reduce in MongoDB, and the performance is not very good. The aggregation framework can be used most of the time, especially when only one table is involved.
db.user.aggregate([ {$group: {_id: '$username', count: {$sum: 1}}} ]);
Please refer to the grammar of aggregation for specific grammar.
a*b
It will be more complicated. What you really need is the value of a*b (pipline1) for each record, and then sum (pipline2):db.user.aggregate([ {$group: {_id: "$username", temp_result: {$multiply: ["$age", "$account"]}}}, {$group: {_id: null, result: {$sum: "$temp_result"}}} ]);