1、aggregate() 方法
我们先插入一些测试数据
{ "_id" : ObjectId("5abc960c684781cda6d38027"), "name" : "郭大爷", "sex" : "男", "age" : 80.0, "skil" : [ "PHP", "Js", "MySql", "Html", "Css" ] } { "_id" : ObjectId("5abc960c684781cda6d38028"), "name" : "郭大爷", "sex" : "男", "age" : 60.0, "skil" : [ "PHP", "MySql" ] } { "_id" : ObjectId("5abc960c684781cda6d38029"), "sex" : "女", "age" : 15.0, "name" : "郭女侠" } { "_id" : ObjectId("5abc960c684781cda6d3802a"), "name" : "郭少爷", "sex" : "男", "age" : 18.0, "skil" : [ "Css", "Java", "Html" ] }
-
求和
查询一下所有人年龄的总和
db.userinfo.aggregate([ { $group : { _id : null, age_sum : { $sum : "$age" } }} ])
结果
{ "_id" : null, "age_sum" : 173.0 }
-
平均值
求所有人年龄的平均值
db.userinfo.aggregate([ { $group:{ _id: null, age_avg: { $avg: "$age" } } } ]);
结果
{ "_id" : null, "age_avg" : 43.25 }
-
最小值
db.userinfo.aggregate([ { $group: { _id: null, age_min: { $min: "$age" } } } ]);
结果
{ "_id" : null, "age_min" : 18.0 }