1 單一分組
分組后不會(huì)展示其他字段, _id為固定寫法,userid為分組字段
# 比如對(duì)比sql:select userid from test group by userid
db.test.aggregate({"$group":{"_id":"$userid"}} )
2 多字段分組
_id為固定寫法吹艇,userid與articleid為分組字段惰蜜,多字段時(shí)需要設(shè)置一個(gè)別名
# 比如對(duì)比sql:select userid,articleid from test group by userid,articleid
db.test.aggregate({"$group":{"_id":{"userid":"$userid","articleid":"$articleid"}}})
3 條件匹配分組
$match表示匹配條件,在group前表示where受神,在后表示having抛猖,userid為分組字段
# 比如對(duì)比sql:select userid from test where userid in("1","2") group by userid
db.test.aggregate(
{"$match":{"userid":{"$in":["1","2"]}}},
{"$group":{"_id":"$userid"}}
)
或者
# 比如對(duì)比sql:select userid,articleid from test where userid in("1","2") group by userid
db.test.aggregate(
{"$match":{"userid":{"$in":["1","2"]}}},
{"$group":{"_id":{"userid":"$userid","articleid":"$articleid"}}}
)
或者h(yuǎn)aving聚合查詢
# 比如:select userid,avg(price) as avg from test where userid >'10' group by userid having avg>35
db.test.aggregate(
{"$match":{"userid":{"$gt":"10"}}},
{"$group":{"_id":"$userid",'avg':{"$avg":"$price"}}},
{"$match":{"avg":{"$gt":35}}}
)
4 分組分頁(yè)排序
限制:skip
db.test.aggregate(
{"$group":{"_id":"$userid"}},
{"$skip":1},
{"$limit":2}
)
5 聚合分組
聚合分組,分為:avg财著、min撑碴、last,聚合結(jié)果需要使用別名醉拓,并且可以結(jié)合條件和排序等元素
5.1 sum聚合-求數(shù)值總和
求某個(gè)數(shù)值總和伟姐,userid分組字段[可以用于多字段聚合],{"price}表示求price合計(jì)
db.test.aggregate({"$group":{"_id":"$userid","total":{"$sum":"$price"}}})
5.2 sum聚合-求分組后數(shù)量
db.test.aggregate({"$group":{"_id":"$userid","total":{"$sum":1}}})
5.3 avg、max亿卤、min聚合
avg愤兵、max、min可以分開使用排吴,也可以一起使用
db.test.aggregate({"$group":{"_id":"$userid","avg":{"$avg":"$price"},"max":{"$max":"$price"},"min":{"$min":"$price"}}})
5.4 復(fù)合聚合
可以多字段聚合求值秆乳,通過sum與avg、max钻哩、min進(jìn)行組合
db.test.aggregate({"$group":{"_id":"$userid"
,"total":{"$sum":"$price"}
,"avg":{"$avg":"$price"}}})
5.5 聚合分組排序
對(duì)聚合結(jié)果進(jìn)行排序屹堰,$sort-排序,avg-聚合結(jié)果的別名憋槐,1:升序双藕,-1:降序
# 先按userid降序,再avg升序
db.test.aggregate({"$group":{"_id":"$userid"
,"avg":{"$avg":"$price"}}}
,{"$sort":{"avg":1}}
,{"$sort":{"_id":-1}})
5.6 首尾取值聚合
last-最后一個(gè)元素
vdb.test.aggregate({"$group":{"_id":"$userid","prices":{"$first":"$price"}}})
5.7 聚合分組拼接
等同于group_concat阳仔,addToSet-元素不可重復(fù),將分組后的數(shù)據(jù)拼接為一個(gè)數(shù)組
db.test.aggregate({"$group":{"_id":"$userid","names":{"$push":"$price"}}})