mongoDB 聚合操做

聚合操做

概念  對文檔進行數據整理和統計函數

聚合函數

 命令spa

db.collection.aggregate()

功能  完成聚合操做, 獲取操做數據code

參數  聚合條件, 配合聚合操做符使用對象

聚合操做符

$group

db.class.aggregate({$group:{_id:"$域名",隨意的名字用於顯示:{$統計操做符:取值}}})

功能  分組聚合 須要配合必定的統計操做符blog

格式  排序

 

{$group:{_id:" ", xxx:{$avg:"$age"}}}

 

 

 

ps:ip

  _id 是固定的字符, 表示被選中做爲分組依據的域文檔

  xxx 爲新增顯示的域名 域名

  xxx 以後的內容就是對這個新增域 的一個數據計算了. 這時候要搭配 聚合操做符了it

 聚合統計操做符

統計求和  $sum

將 class 集合 按照 sex 分組, 而後計算每一個 分組的人數, 最後賦值給 num 字段來展現
>
db.class.aggregate({$group:{_id:"$sex",num:{$sum:1}}}) { "_id" : "g", "num" : 2 } { "_id" : "b", "num" : 1 } { "_id" : null, "num" : 13 }
 按照 性別分組 後計算 age 的綜合
 > db.class.aggregate({$group:{_id:"$sex",Age:{$sum:"$age"}}})
 { "_id" : "g", "Age" : 36 }
 { "_id" : "b", "Age" : 75 }

求平均數  $avg

按照 性別 分組後, 新增 Age 列, 內容爲 age 域的平均值
>
db.class1.aggregate({$group:{_id:"$sex",Avg:{$avg:"$age"}}}) { "_id" : "g", "Avg" : 26.666666666666668 } { "_id" : "b", "Avg" : 41.333333333333336 }

求最大值 / 最小值  $max / $min

按照 性別 分組後, 新增 mum 列, 內容爲 age 域的最大值
>
db.class1.aggregate({$group:{_id:"$sex",mum:{$max:"$age"}}}) { "_id" : "g", "mum" : 36 } { "_id" : "b", "mum" : 78 }


按照 性別 分組後, 新增 mum 列, 內容爲 age 域的最大值
> db.class1.aggregate({$group:{_id:"$sex",mum:{$min:"$age"}}})
{ "_id" : "g", "mum" : 18 }
{ "_id" : "b", "mum" : 18 }

求首/ 末值  $first / $last

按照 性別 分組後, 新增 mum 列, 內容爲 age 域的第一個值
> db.class1.aggregate({$group:{_id:"$sex",mum:{$first:"$age"}}})
{ "_id" : "g", "mum" : 18 }
{ "_id" : "b", "mum" : 18 }
按照 性別 分組後, 新增 mum 列,  內容爲 age 域的最後一個值
> db.class1.aggregate({$group:{_id:"$sex",mum:{$last:"$age"}}})
{ "_id" : "g", "mum" : 36 }
{ "_id" : "b", "mum" : 78 }
>

獲取指定域的集合文檔數據  $project

只顯示 name , age 域
> db.class1.aggregate({$project:{_id:0,name:1,age:1}})
{ "name" : "aa", "age" : 18 }
{ "name" : "bb", "age" : 28 }
{ "name" : "cc", "age" : 78 }
{ "name" : "dd", "age" : 18 }
{ "name" : "ee", "age" : 26 }
{ "name" : "ff", "age" : 36 }
只顯示 name , age 域, 且 重命名爲 Name 和 Age
> db.class1.aggregate({$project:{_id:0,Name:"$name",Age:"$age"}})
{ "Name" : "aa", "Age" : 18 }
{ "Name" : "bb", "Age" : 28 }
{ "Name" : "cc", "Age" : 78 }
{ "Name" : "dd", "Age" : 18 }
{ "Name" : "ee", "Age" : 26 }
{ "Name" : "ff", "Age" : 36 }

數據篩選  $match

$match 值 寫法同 query 參數

篩選年齡大於等於 20 的文檔
> db.class1.aggregate({$match:{age:{$gt:20}}})

顯示前幾條  $limit

顯示前三條文檔
> db.class1.aggregate({$limit:3})

跳過前幾條文檔顯示後面內容  $skip

跳過前3條顯示後面內容
> db.class1.aggregate({$skip:3})

排序  $sort

將集合文檔按照年齡升序排序
> db.class1.aggregate({sort:{age:1}})

聚合管道

定義  將多個聚合操做合併在一塊兒完成.即將上一個聚合的操做結果做爲下一個聚合的操做對象,直到全部的操做完成

> db.class1.aggregate([{},{},{}}

實例

按照年齡排序後, 不顯示 _id
> db.class1.aggregate([{$sort:{age:1}},{$project:{_id:0}}])
相關文章
相關標籤/搜索