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实现,或者用其他方法实现也可以
???????????????????
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.
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):var map = function(){
var reduce = function(key,values){
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