關(guān)于mongoDB的聚合操作_aggregate()歸納詳解
mongoDB聚合操作
mongoDB聚合常用的管道有
- $match: 過濾管道過濾數(shù)據(jù),只輸出符合條件的文檔
- $group: 將集合中的文檔分組,可用于統(tǒng)計結(jié)果
- $project 映射管道,映射輸出
- $sort: 排序管道,將輸入文檔排序后輸出
- $limit: 限制管道,限制聚合管道返回的文檔書
- $skip: 跳過管道,跳過指定數(shù)量的文檔,并返回余下的文檔
1.準(zhǔn)備一組數(shù)據(jù)
db.data.insertMany([{name:"Tom", city:"cityA",type:"aaa",num:609,age:18}, {name : "allen", city :"cityC", type: "bbb", num : 549,age:20}, {name :"jerry", city :"cityA", type :"bbb", num : 593,age:22}, {name :"frank", city : "cityB", type:"aaa", num : 657,age:21}, {name :"jack", city : "cityC", type:"aaa", num : 620,age:18}, {name :"alice", city : "cityB", type:"ccc", num : 584,age:20}, {name :"marry", city:"cityA", type:"bbb", num : 599,age:22} ])
db.data.find()
2.$group 分組管道
2.1 統(tǒng)計單組
對city分組,并求每組num的平均值。
db.data.aggregate({$group:{_id:'$city',avg_num:{$avg:'$num'}}})
2.2 統(tǒng)計多組
db.data.aggregate({$group:{_id:'$city',avg_num:{$avg:'$num'},avg_age:{$avg:'$age'}}})
3.$match 過濾管道
可以將其作用結(jié)果傳給后一個管道。
對city不是"cityC"的city分組(過濾掉“”cityC"),并求每組num的平均值。
db.data.aggregate({$match:{city:{$ne:"cityC"}}},{$group:{_id:'$city',avg_num:{$avg:'$num'}}})
對age≥20的city分組(過濾掉“”cityC"),并求每組num的平均值。
db.data.aggregate({$match:{age:{$gte:20}}},{$group:{_id:'$city',avg_num:{$avg:'$num'}}})
其中,
_id是分組的依據(jù)
avg_num是新定義的字段名
$avg 是求值方法的表達(dá)式,這里是求平均值的表達(dá)式
‘$city’ 指定的分組依據(jù)
‘$num’ 指定的要求值的字段
拓展 統(tǒng)計數(shù)據(jù)個數(shù)
如果要統(tǒng)計每組數(shù)據(jù)的個數(shù),則可以使用 $sum 實(shí)現(xiàn)。
$sum的功能是求某字段的和,用$sum計數(shù)時,如統(tǒng)計每個city的人數(shù),可以寫成:
db.data.aggregate({$group:{_id:'$city',count:{$sum:1}}})
即對字段,常數(shù)1進(jìn)行計數(shù)。如果寫為{$sum:2},則計數(shù)結(jié)果為4,4,6。
4.$project 映射管道
db.data.aggregate({$group:{_id:'$city',avg_num:{$avg:'$num'},avg_age:{$avg:'$age'}}},{$project:{avg_num:1}})
如圖,結(jié)果不再顯示avg_age,只顯示了_id和avg_num。
5.$sort $skip $limit
按年齡降序排列,跳過第一條,取前三條數(shù)據(jù)
db.data.aggregate({$sort:{age:-1}},{$skip:1},{$limit:3})
按年齡降序排列,取前三條數(shù)據(jù),跳過第一條,
db.data.aggregate({$sort:{age:-1}},{$limit:3},{$skip:1})
取前三個數(shù)據(jù),跳過第一個,再降序排列
db.data.aggregate({$limit:3},{$skip:1},{$sort:{age:-1}})
管道的寫法不用考慮優(yōu)先級的問題,從左到右依次執(zhí)行。
6.常用表達(dá)式補(bǔ)充
$sum: 計算總和, $sum:1 表示以?倍計數(shù)
$avg: 計算平均值
$min: 獲取最?值
$max: 獲取最?值
$push: 在結(jié)果?檔中插?值到?個數(shù)組中
$first: 根據(jù)資源?檔的排序獲取第?個?檔數(shù)據(jù)
$last: 根據(jù)資源?檔的排序獲取最后?個?檔數(shù)據(jù)
到此這篇關(guān)于關(guān)于mongoDB的聚合操作_aggregate()歸納詳解的文章就介紹到這了,更多相關(guān)mongoDB的聚合操作內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
基于?MongoTemplate實(shí)現(xiàn)MongoDB的復(fù)雜查詢功能
本文介紹了如何使用MongoTemplate進(jìn)行復(fù)雜的MongoDB查詢,展示了如何進(jìn)行分頁和排序查詢,通過示例代碼,展示了如何處理不同類型的查詢,如單條件查詢、模糊查詢、組合條件查詢以及分頁排序查詢,感興趣的朋友跟隨小編一起看看吧2024-12-12