MongoDB聚合(aggregate)


一、基礎

1、什么是聚合?

聚合是基於數據處理的聚合管道,每個文檔通過一個有多個階段(stage)組成的管道
可以對每個階段的管道進行分組、過濾等功能,然后經過一系列的處理,輸出相應的結果

db.集合名稱.aggregate({管道: {表達式}})

有點像Django中ORM聚合的語法

2、常用管道

$group: 將集合中的文檔分組,用於統計結果
$match: 過濾數據,只輸出符合條件的文檔
$project: 修改輸入文檔的結構,如重命名、增加、刪除字段、創建計算結果

$sort: 將輸入文檔排序后輸出
$limit: 限制聚合管道返回的文檔數
$skip: 跳過指定數量的文檔,並返回余下的文檔
$unwind(): 將列表(數組)類型的字段進行拆分

3、常用表達式

處理輸入文檔,並輸出
語法: 表達式:'$列名'
常用表達式
$sum: 計算總和, $sum:1 表示以一倍計數
$avg: 計數平均值
$min: 獲取最小值
$max: 獲取最大值
$push: 在結果文檔中插入值到一個數組中
$first: 根據資源文檔的排序獲取第一個文檔數據
$last: 根據資源文檔的排序獲取最后一個文檔數據

二、常用管道用法

1、$group

作用: 將集合中的文檔分組,可用於統計結果
_id表示分組的依據,使用某個字段的格式為'$字段'
格式
db.集合名稱.aggregate({$group:{ _id: '$字段', 自定義字段: {表達式: '$字段'}}})

db.stu.aggregate({$group: {_id: '$gender'}})
db.stu.aggregate({$group: {_id: '$gender', count: {$sum: 1}}})
db.stu.aggregate({$group: {_id: '$gender', avg_age: {$avg: '$age'}}})
db.stu.aggregate({$group: {_id: '$hometown', min_age: {$min: '$age'}, count: {$sum: 1}}})

注意: 
    _id后面的值,表示按照什么分組,格式'$字段'
    count, avg_count是自定義的字段
    表達式的值是'$字段'

Group by null

將集合中所用文檔分為一組,即該集合就是一個組
# 求學生的總量和平均年齡
db.stu.aggregate({$group: {_id: null, count:{$sum: 1}, avg_age:{$avg: '$age'}}})

補充

# 插入數據

db.test.insert({country: "china", province: "sh", userid: "a"})
db.test.insert({country: "china", province: "sh", userid: "b"})
db.test.insert({country: "china", province: "sh", userid: "a"})
db.test.insert({country: "china", province: "sh", userid: "c"})
db.test.insert({country: "china", province: "bj", userid: "da"})
db.test.insert({country: "china", province: "bj", userid: "fa"})

# 1.去重
能夠同時按照多個鍵進行分組,若文檔中的每個字段都進行分組,那么可以實現去重的功能
db.test.aggregate({$group: {_id: {country: '$country', province: '$province'}}})
# 2.取字典嵌套的字典中的值 
_id: {contry: '$_id.country'}
例子
db.test.aggregate(
{$group: {_id: {country: '$country', province: '$province', userid: '$userid'}}},  
{$group: {_id: {country: '$_id.country', province: '$_id.province'}, count: {$sum: 1}}}, 
{$project: {country: '$_id.country', province: '$_id.province', count: '$count', _id: 0}}
)

2、$project

作用:修改輸入文檔的結構,如重命名、增加(顯示)、刪除(隱藏)字段,創建計算結果
1.顯示和隱藏
格式: 
db.集合名稱.aggregate({$project: {_id: 0, 字段:1}})
值為0,是隱藏
值為1,是顯示
示例
db.stu.aggregate({$project: {_id: 0, name: 1, hometown: 1, age: 1, gender: 1}})
注意: 顯示、隱藏字段和投影差不多
2.重命名
例子
db.stu.aggregate({$group: {_id: '$gender', count: {$sum: 1}, avg: {$avg: '$age'}}}, {$project: {_id: 0,gender: '$_id', counter: '$count', avg_age: '$avg'}})
注意: 
重命名字段格式 {新的字段名: '$舊的字段名稱'}
管道符之間用逗號隔

3、$match

作用: 用於過濾數據,只輸出符合條件的文檔
注意: match是管道命令,能將結果交給下一個管道,find不可以
例子
db.stu.aggregate({$match: {age: {$lte: 18}}})
# 過濾->分組->重命名、顯示
db.stu.aggregate({$match: {age: {$lte: 18}}}, {$group: {_id: '$gender', count: {$sum: 1}}}, {$project: {gender: '$_id', _id: 0, count: 1}})

 4、$limit和$skip

$limit
限制聚合管道返回的文檔數
例子
db.stu.aggregate({$limit: 2})

$skip
跳過指定數量的聚合管道文檔。並返回剩下的文檔
例子
db.stu.aggregate({$skip: 2})
db.stu.aggregate({$limit: 2}, {$skip: 3})
注意順序:先寫skip,再寫limit

5、$unwind

# unwind 解開,松開
作用: 將文檔中的某一個數組類型字段拆分成多條,每條包含數組中的一個值
格式:
db.集合名稱.aggregate({$unwind: '$字段名稱'})
例子
db.t2.insert({_id: 1, item:'t-shirt', size: ['S', 'M', 'L']})
db.t2.aggregate({$unwind: '$size'})
結果:
{ "_id" : 1, "item" : "t-shirt", "size" : "S" }
{ "_id" : 1, "item" : "t-shirt", "size" : "M" }
{ "_id" : 1, "item" : "t-shirt", "size" : "L" }

# 補充

db.集合名稱.aggregate({
    $unwind: {
        path: '$字段名稱',
        preserveNullAndEmptyArrays: <boolean>  # 防止數據丟失
    }
})
屬性preserveNullAndEmptyArrays值
為false表示拋棄屬性值為空的文檔
為true表示保留屬性值為空的文檔

例子
db.t3.aggregate({$unwind: {path: '$size', preserveNullAndEmptyArrays: false}})

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM