MongoDB聚合有啥用处?如何使用?
发布时间:2022-04-22 10:22:47 所属栏目:系统 来源:互联网
导读:这篇文章主要给大家分享MongoDB聚合的用处以及操作,小编觉得是比较挺实用的,因此分享给大家做个参考,感兴趣的朋友就继续往下看吧。 MongoDB 聚合 MongoDB中聚合(aggregate)主要用于处理数据(诸如统计平均值,求和等),并返回计算后的数据结果。有点类似sql
这篇文章主要给大家分享MongoDB聚合的用处以及操作,小编觉得是比较挺实用的,因此分享给大家做个参考,感兴趣的朋友就继续往下看吧。 MongoDB 聚合 MongoDB中聚合(aggregate)主要用于处理数据(诸如统计平均值,求和等),并返回计算后的数据结果。有点类似sql语句中的 count(*)。 基本语法为:db.collection.aggregate( [ <stage1>, <stage2>, ... ] ) 现在在mycol集合中有以下数据: { "_id" : 1, "name" : "tom", "sex" : "男", "score" : 100, "age" : 34 } { "_id" : 2, "name" : "jeke", "sex" : "男", "score" : 90, "age" : 24 } { "_id" : 3, "name" : "kite", "sex" : "女", "score" : 40, "age" : 36 } { "_id" : 4, "name" : "herry", "sex" : "男", "score" : 90, "age" : 56 } { "_id" : 5, "name" : "marry", "sex" : "女", "score" : 70, "age" : 18 } { "_id" : 6, "name" : "john", "sex" : "男", "score" : 100, "age" : 31 } 1、$sum计算总和。 Sql: select sex,count(*) frommycol group by sex MongoDb: db.mycol.aggregate([{$group: {_id: '$sex', personCount: {$sum: 1}}}]) 2、$avg 计算平均值 Sql: select sex,avg(score) avgScore frommycol group by sex Mongodb: db.mycol.aggregate([{$group: {_id: '$sex', avgScore: {$avg: '$score'}}}]) 3、$max获取集合中所有文档对应值得最大值。 Sql: select sex,max(score) maxScore frommycol group by sex Mongodb: db.mycol.aggregate([{$group: {_id: '$sex', maxScore: {$max: '$score'}}}]) 4、$min 获取集合中所有文档对应值得最小值。 Sql: select sex,min(score) minScore frommycol group by sex Mongodb: db.mycol.aggregate([{$group: {_id: '$sex', minScore: {$min: '$score'}}}]) 5、$push 把文档中某一列对应的所有数据插入值到一个数组中。 Mongodb: db.mycol.aggregate([{$group: {_id: '$sex', scores : {$push: '$score'}}}]) 6、 全部统计null db.mycol.aggregate([{$group:{_id:null,totalScore:{$push:'$score'}}}]) (编辑:开发网_开封站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |