聚合aggregate
統計功能,用來計算數據
db.集合名稱.aggregate([{管道:{表達式}}])
管道(|):把上一次的結果輸出,作爲下次結果的輸入
聚合框架中常用的幾個操作:
- $project:修改輸入文檔的結構。可以用來重命名、增加或刪除域,也可以用於創建計算結果以及嵌套文檔。
- $match:用於過濾數據,只輸出符合條件的文檔。$match使用MongoDB的標準查詢操作。
- $limit:用來限制MongoDB聚合管道返回的文檔數。
- $skip:在聚合管道中跳過指定數量的文檔,並返回餘下的文檔。
- $unwind:將文檔中的某一個數組類型字段拆分成多條,每條包含數組中的一個值。
- $group:將集合中的文檔分組,可用於統計結果。
- $sort:將輸入文檔排序後輸出。
- $geoNear:輸出接近某一地理位置的有序文檔。
$Group
- counter : 結果字段
- {$sum:1} : 每一行+1
- $sum : 前面加%$, 表示屬性
- 1表示統計個數
- _id:null : 將整個集合分成一組
db.stu.aggregate(
{$group:{_id:'$age',counter:{$sum:1}}}
)
# 按照年齡求和
db.stu.aggregate(
{$group:{_id:'$age',counter:{$sum:'$age'}}}
)
# avg:平均值 min/max/first/last/push ...
push: 把基於counter分組結果加到數組中去
輸出:
{
"_id" : 13.0,
"counter" : [
13.0,
13.0,
13.0
]
}
獲取整個文檔:$$ROOT
db.stu.aggregate(
{$group:{_id:'$age',counter:{$push:'$$ROOT'}}}
)
輸出:
{
"_id" : 23.0,
"counter" : [
{
"_id" : ObjectId("59cd646e68b8b37683687a6d"),
"name" : "dimples",
"age" : 23.0
}
]
}
$match
- 用於過濾數據,只輸出符合條件的文檔
- 使用MongoDB的標準查詢操作
查詢年齡>20的學生
db.stu.aggregate(
{$match:{age: {$gt:20}}}
)
查詢年齡>10的人數
db.stu.aggregate(
{$match:{age: {$gt:10}}},
{$group:{
_id:'$age',
counter:{$sum:1}
}}
)
$project 投影
- 修改輸入文檔的結構(顯示那些字段..)
基於: 查詢年齡>10的人數,顯示counter
db.stu.aggregate(
{$match:{age: {$gt:10}}},
{$group:{
_id:'$age',
counter:{$sum:1}
}},
{$project:{_id:0,counter:1}}
)
$sort
- 基於$group之後寫
排序
db.stu.aggregate(
{$match:{age: {$gt:10}}},
{$group:{
_id:'$age',
counter:{$sum:1}
}},
{$project:{_id:1,counter:1}},
{$sort:{_id:1}}
)
$unwind拆分數組
- 把文檔中的某一個數組類型字段拆分成多條,每條包含數組中的一個值
- 從輸入文檔中解構一個數組字段,以輸出每個元素的文檔。每個輸出文檔都是由元素替換的數組字段的值的輸入文檔。
對某字段值進行拆分
db.集合名稱.aggregate([{$unwind:'$字段名稱'}])
構造數據:
db.p2.insert({_id:1,title:'t-shirt',size:['M','L','S']})
查詢:
db.p2.aggregate([
{$unwind:'$size'}
])
處理空數組、無字段、null情況
- includeArrayIndex : 用於保存元素的數組索引的新字段的名稱。該名稱不能以美元符號開始$。
- preserveNullAndEmptyArrays(boolean)
- 如果true,如果path爲空,缺少或空數組,則 $unwind輸出文檔。不會丟失。
- 如果false,如果$unwind文件path爲空,丟失或空數組, 則不輸出文檔。會丟失。
db.p2.aggregate([
{$unwind:{
path:'$size',
preserveNullAndEmptyArrays:true
}}
])
db.stu.aggregate([
{$group:{_id:'$age',counter:{$sum:1},docs:{$push:'$$ROOT'}}},
{$project:{_id:0,counter:1,docs:1}},
{$unwind:'$docs'}
])