others - 在mongodb中,Select Max() GROUP BY

请帮助我将选择语句转换为mongodb:


Select Name, Max(Value) From table1 Group By Name



我阅读了这个文档:http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Group

谢谢

时间:

按照如下方式创建了Mongo集合。


{"_id" : ObjectId("4fb36bfd3d1c88bfa15103b1"),"name" :"bob","value" : 5 }


{"_id" : ObjectId("4fb36c033d1c88bfa15103b2"),"name" :"bob","value" : 3 }


{"_id" : ObjectId("4fb36c063d1c88bfa15103b3"),"name" :"bob","value" : 7 }


{"_id" : ObjectId("4fb36c0c3d1c88bfa15103b4"),"name" :"john","value" : 2 }


{"_id" : ObjectId("4fb36c103d1c88bfa15103b5"),"name" :"john","value" : 4 }


{"_id" : ObjectId("4fb36c143d1c88bfa15103b6"),"name" :"john","value" : 8 }


{"_id" : ObjectId("4fb36c163d1c88bfa15103b7"),"name" :"john","value" : 6 }



然后,通过使用下面的代码,我将它按名称和max(value ) 分组,


db.table1.group(


 {key: {name:true},


 reduce: function(obj,prev) { 


 if (prev.maxValue < obj.value) { 


 prev.maxValue = obj.value; 


 } 


 },


 initial: { maxValue: 0 }}


);



结果显示为


[


 {


"name" :"bob",


"maxValue" : 7


 },


 {


"name" :"john",


"maxValue" : 8


 }


]



使用聚合框架要简单得多,你可以使用聚合框架在下面的代码中得到相同的结果。


db.table1.aggregate(


 {$group:{_id:"$name","maxValue": {$max:"$value"}}}


);



使用聚合框架:


db.table1.aggregate({$group:{\'_id\':\'$name\', \'max\':{$max:\'$value\'}}}, 


{$sort:{\'max\':1}}).result




var myresult = db.table1.aggregate([{ 


 $group: {


 _id:"$Name", 


 value: { $max:"$Value" } 


 } 


}]);


print(myresult)



既然MongoDB支持mapreduce,下面就可以做到。


db.employee.insert({name:"Tejas",Value:2})


db.employee.insert({name:"Tejas",Value:3})


db.employee.insert({name:"Varma",Value:1})


db.employee.insert({name:"Varma",Value:6})



var map=function(){


var key={name:this.name};


var value={value:this.Value};


emit(key,value);


};



var reduce=function(key,values){


var max=-1;


values.forEach(function(value){


 if(max==-1){


 max=value[\'value\'];


 }


 if(max<value[\'value\']){


 max=value[\'value\'];


 }


});


return {max:max};


};



db.employee.mapReduce(map ,reduce , {out:{inline:1} }) ;

...