MongoDB聚合操作(Shell)

0、数据准备

for(var i=0;i<10000;i++){
var patid="pat"+i;
var patname="name"+i;
var sex="M";
var age=parseInt(100*Math.random(i));
db.patient.insert({"patid":patid,"patname":patname,"sex":sex,"age":age,address:{"city":"shanghai","street":"huaihai road"}});
}

1、count

db.patient.count({"age":12})

2、distinct

db.patient.distinct("age")

3、min, max, sum,avg

db.patient.aggregate([{$group:{_id:"$item",maxAge:{$max:"$age"}}}])
db.patient.aggregate([{$group:{_id:"$item",minAge:{$min:"$age"}}}])
db.patient.aggregate([{$group:{_id:"$item",sumAge:{$sum:"$age"}}}])
db.patient.aggregate([{$group:{_id:"$item",avgAge:{$avg:"$age"}}}])

4、group

db.patient.group({
"key":{"age":true},
"initial":{"patids":[]},
"reduce":function(item,out){out.patids.push(item.patid);},
"finalize":function(out){out.count=out.patids.length;},
"condition":{"age":{$lte:18}}
})

5、map reduce

map=function(){emit(this.age,1);}
reduce=function(key,values){return values.length;}
mropt={"out":"mrresult"}
db.patient.mapReduce(map,reduce,mropt).find()

Leave a Reply

Your email address will not be published. Required fields are marked *

*