1、聚合函数
-
查询总数 .count()
> db.userinfo.count() 3 > db.userinfo.find() { "_id" : 1, "name" : "郭大爷", "sex" : "男", "age" : "80" } { "_id" : 2, "name" : "郭老师", "sex" : "男", "age" : "不详" } { "_id" : 3, "name" : "郭少爷", "sex" : "男", "age" : "18" }
2、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" : "女" } { "_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" : 158.0 }
-
平均值
-
最小值
-
最大值
-
获取第一个文档
-
获取最后一个文档