mongodb

新建collection 名称    test
建表网络上太多了,省略,表中的内容
mongos> db.test.find();
{ "_id" : ObjectId("4ee7125f0f3210cf35a32f02"), "name" : "xm01", "age" : 10 }
{ "_id" : ObjectId("4ee712a80f3210cf35a32f03"), "name" : "xm02", "age" : 20 }
{ "_id" : ObjectId("4ee712c60f3210cf35a32f04"), "name" : "xm01", "age" : 30 }
{ "_id" : ObjectId("4ee712d20f3210cf35a32f05"), "name" : "xm02", "age" : 20 }
{ "_id" : ObjectId("4ee712d70f3210cf35a32f06"), "name" : "xm03", "age" : 20 }
{ "_id" : ObjectId("4ee7173d0f3210cf35a32f07"), "name" : "xm02", "age" : 10 }

下面对name做group by ,对age做汇总
定义 map函数
m=function(){emit(this.name,{age:this.age})};
定义reduce函数
r=function(key,values){var result={age:0}; values.forEach( function(v){result.age +=v.age; } ); return result};
调用mapreduce执行group by查询
mongos> db.runCommand({
... mapreduce:"test",     //执行分组的集合
... map:m,                    //map函数,循环集合对象
... reduce:r,                  //reduce函数,对document做汇总
... out:"res"                  //输出结果
... })
结果显示:
db.res.find();
mongos> db.res.find();
{ "_id" : "xm01", "value" : { "count" : 2, "age" : 40 } }
{ "_id" : "xm02", "value" : { "count" : 3, "age" : 50 } }
{ "_id" : "xm03", "value" : { "count" : 1, "age" : 20 } }

你可能感兴趣的:(mongodb)