MongoDB數(shù)據(jù)庫(kù)聚合之分組統(tǒng)計(jì)$group的用法詳解
前言
MongoDB不像關(guān)系型數(shù)據(jù)庫(kù),普通的查詢不支持匯總,要進(jìn)行復(fù)雜的分組匯總,需要使用聚合管道,$group可以說(shuō)是MongoDB聚合管道進(jìn)行數(shù)據(jù)分析最常用的一個(gè)階段。該階段根據(jù)分組鍵值(組鍵)把文檔分成若干組,每個(gè)唯一的鍵值對(duì)應(yīng)一個(gè)文檔。組鍵通常是一個(gè)或多個(gè)字段,也可以是表達(dá)式的結(jié)果。$group階段輸出的結(jié)果中,_id字段的值就是組鍵的值,輸出文檔中還可以包含匯總表達(dá)式的字段,匯總表達(dá)式的功能非常豐富,下面的列表會(huì)簡(jiǎn)單介紹,具體的使用方法可以參考詳細(xì)說(shuō)明。
$group的語(yǔ)法
{
$group:
{
_id: <expression>, // 組鍵,就是分組的鍵值字段或表達(dá)式
<field1>: { <accumulator1> : <expression1> },
...
}
}
字段說(shuō)明:
| 字段 | 說(shuō)明 |
|---|---|
| _id | 不可省略,通過(guò)_id表達(dá)式指定分組的依據(jù),如果直接指定_id的值為null或常量,則把全部的輸入文檔匯總后返回一個(gè)文檔 |
| field | 可選,匯總表達(dá)式計(jì)算的結(jié)果 |
| _id和field可以是任何合法的表達(dá)式。 |
分組匯總操作符
分組匯總操作符比較多,功能豐富且強(qiáng)大,這里簡(jiǎn)要介紹其用途,詳細(xì)的用法后續(xù)再專文介紹。
| 操作符 | 用途介紹 |
|---|---|
$accumulator | 返回累加結(jié)果 |
$addToSet | 把分組中不重復(fù)的表達(dá)式的值作為數(shù)組返回,注意數(shù)組的元素?zé)o序的,類似分組內(nèi)的distinct |
$avg | 返回?cái)?shù)值的平均值。非數(shù)值會(huì)被忽略 |
$bottom | 按照指定的順序返回分組中最后一個(gè)元素 |
$bottomN | 按照指定的順序返回分組中最后N個(gè)元素字段的集合,如果分組元素?cái)?shù)量小于N,則返回全部 |
$count | 返回分組內(nèi)的元素?cái)?shù)量 |
$first | 返回分組內(nèi)第一個(gè)元素表達(dá)式的結(jié)果 |
$firstN | 返回分組內(nèi)前n個(gè)元素的聚合。只有文檔有序時(shí)才有意義 |
$last | 返回分組中最后一個(gè)文檔的表達(dá)式的結(jié)果 |
$lastN | 返回分組內(nèi)最后n個(gè)元素的聚合。只有文檔有序時(shí)才有意義 |
$max | 返回每個(gè)分組表達(dá)式值的最大值 |
$maxN | 返回分組內(nèi)最大的n個(gè)元素的集合 |
$median | 返回分組中的中位數(shù) |
$mergeObjects | 返回分組合并后的文檔 |
$min | 返回分組內(nèi)表達(dá)式的最小值 |
$percentile | 返回與指定百分位數(shù)值相對(duì)應(yīng)的值的數(shù)組 |
$push | 返回每個(gè)分組表達(dá)式值的數(shù)組 |
$stdDevPop | 返回標(biāo)準(zhǔn)差 |
$stdDevSamp | 返回樣本標(biāo)準(zhǔn)差 |
$sum | 返回合計(jì)值,忽略空值 |
$top | 根據(jù)指定的順序返回組內(nèi)最前面的元素 |
$topN | 根據(jù)指定的順序返回組內(nèi)前N個(gè)元素的聚合 |
注意
$group使用內(nèi)存不能超過(guò)100M,超過(guò)會(huì)報(bào)錯(cuò)。如果想要處理更多數(shù)據(jù)或者少用一些內(nèi)存,可使用allowDiskUse選項(xiàng)把數(shù)據(jù)寫入臨時(shí)文件。- 當(dāng)使用
$first、$last等操作符時(shí),可以考慮在參與排序的分組字段上添加索引,某些情況下,這些操作可以使用索引快速定位到相應(yīng)的記錄。
一些例子
統(tǒng)計(jì)數(shù)量
創(chuàng)建并插入數(shù)據(jù):
db.sales.insertMany([
{ "_id" : 1, "item" : "abc", "price" : Decimal128("10"), "quantity" : Int32("2"), "date" : ISODate("2014-03-01T08:00:00Z") },
{ "_id" : 2, "item" : "jkl", "price" : Decimal128("20"), "quantity" : Int32("1"), "date" : ISODate("2014-03-01T09:00:00Z") },
{ "_id" : 3, "item" : "xyz", "price" : Decimal128("5"), "quantity" : Int32( "10"), "date" : ISODate("2014-03-15T09:00:00Z") },
{ "_id" : 4, "item" : "xyz", "price" : Decimal128("5"), "quantity" : Int32("20") , "date" : ISODate("2014-04-04T11:21:39.736Z") },
{ "_id" : 5, "item" : "abc", "price" : Decimal128("10"), "quantity" : Int32("10") , "date" : ISODate("2014-04-04T21:23:13.331Z") },
{ "_id" : 6, "item" : "def", "price" : Decimal128("7.5"), "quantity": Int32("5" ) , "date" : ISODate("2015-06-04T05:08:13Z") },
{ "_id" : 7, "item" : "def", "price" : Decimal128("7.5"), "quantity": Int32("10") , "date" : ISODate("2015-09-10T08:43:00Z") },
{ "_id" : 8, "item" : "abc", "price" : Decimal128("10"), "quantity" : Int32("5" ) , "date" : ISODate("2016-02-06T20:20:13Z") },
])
統(tǒng)計(jì)sales全部文檔數(shù)量
相當(dāng)于collection.find({}).count()
db.sales.aggregate( [
{
$group: {
_id: null,
count: { $count: { } }
}
}
] )
結(jié)果:
{ "_id" : null, "count" : 8 }
檢索不同的值,等價(jià)于distinct
仍以上例的sales集合數(shù)據(jù)為例
db.sales.aggregate( [ { $group : { _id : "$item" } } ] )
結(jié)果:
{ "_id" : "abc" }
{ "_id" : "jkl" }
{ "_id" : "def" }
{ "_id" : "xyz" }
等價(jià)于:
db.sales.distinct("item")
按Item分組
下面的聚合先按照item進(jìn)行分組,計(jì)算每個(gè)item銷售總額,并且返回大于等于100的item。
db.sales.aggregate(
[
//階段1
{
$group :
{
_id : "$item",
totalSaleAmount: { $sum: { $multiply: [ "$price", "$quantity" ] } }
}
},
//階段2
{
$match: { "totalSaleAmount": { $gte: 100 } }
}
]
)
階段1:$group階段,根據(jù)item進(jìn)行分組,并計(jì)算每個(gè)item的銷售總額。
階段2:$math階段,過(guò)濾結(jié)果文檔,只返回銷售總額totalSaleAmount大于等于100的文檔。
結(jié)果:
{ "_id" : "abc", "totalSaleAmount" : Decimal128("170") }
{ "_id" : "xyz", "totalSaleAmount" : Decimal128("150") }
{ "_id" : "def", "totalSaleAmount" : Decimal128("112.5") }
計(jì)算總數(shù)、合計(jì)和平均值
創(chuàng)建一個(gè)sales集合并插入記錄:
db.sales.insertMany([
{ "_id" : 1, "item" : "abc", "price" : Decimal128("10"), "quantity" : Int32("2"), "date" : ISODate("2014-03-01T08:00:00Z") },
{ "_id" : 2, "item" : "jkl", "price" : Decimal128("20"), "quantity" : Int32("1"), "date" : ISODate("2014-03-01T09:00:00Z") },
{ "_id" : 3, "item" : "xyz", "price" : Decimal128("5"), "quantity" : Int32( "10"), "date" : ISODate("2014-03-15T09:00:00Z") },
{ "_id" : 4, "item" : "xyz", "price" : Decimal128("5"), "quantity" : Int32("20") , "date" : ISODate("2014-04-04T11:21:39.736Z") },
{ "_id" : 5, "item" : "abc", "price" : Decimal128("10"), "quantity" : Int32("10") , "date" : ISODate("2014-04-04T21:23:13.331Z") },
{ "_id" : 6, "item" : "def", "price" : Decimal128("7.5"), "quantity": Int32("5" ) , "date" : ISODate("2015-06-04T05:08:13Z") },
{ "_id" : 7, "item" : "def", "price" : Decimal128("7.5"), "quantity": Int32("10") , "date" : ISODate("2015-09-10T08:43:00Z") },
{ "_id" : 8, "item" : "abc", "price" : Decimal128("10"), "quantity" : Int32("5" ) , "date" : ISODate("2016-02-06T20:20:13Z") },
])
按照日期分組
下面的聚合管道計(jì)算2014年的銷售總額、平均銷量和銷售數(shù)量
db.sales.aggregate([
//階段1
{
$match : { "date": { $gte: new ISODate("2014-01-01"), $lt: new ISODate("2015-01-01") } }
},
//階段2
{
$group : {
_id : { $dateToString: { format: "%Y-%m-%d", date: "$date" } },
totalSaleAmount: { $sum: { $multiply: [ "$price", "$quantity" ] } },
averageQuantity: { $avg: "$quantity" },
count: { $sum: 1 }
}
},
//階段3
{
$sort : { totalSaleAmount: -1 }
}
])
階段1使用$math只允許2014年的數(shù)據(jù)進(jìn)入下一階段.
階段2使用$group根據(jù)日期進(jìn)行分組,統(tǒng)計(jì)每個(gè)分組的銷售總額、平均銷量和銷售數(shù)量。
階段3使用$sort按照銷售總額進(jìn)行降序排序
結(jié)果:
{
"_id" : "2014-04-04",
"totalSaleAmount" : Decimal128("200"),
"averageQuantity" : 15, "count" : 2
}
{
"_id" : "2014-03-15",
"totalSaleAmount" : Decimal128("50"),
"averageQuantity" : 10, "count" : 1
}
{
"_id" : "2014-03-01",
"totalSaleAmount" : Decimal128("40"),
"averageQuantity" : 1.5, "count" : 2
}
按控制null分組
下面的聚合操作,指定分組_id為空,計(jì)算集合中所有文檔的總銷售額、平均數(shù)量和計(jì)數(shù)。
db.sales.aggregate([
{
$group : {
_id : null,
totalSaleAmount: { $sum: { $multiply: [ "$price", "$quantity" ] } },
averageQuantity: { $avg: "$quantity" },
count: { $sum: 1 }
}
}
])
結(jié)果:
{
"_id" : null,
"totalSaleAmount" : Decimal128("452.5"),
"averageQuantity" : 7.875,
"count" : 8
}
數(shù)據(jù)透視
創(chuàng)建books集合并插入數(shù)據(jù)
db.books.insertMany([
{ "_id" : 8751, "title" : "The Banquet", "author" : "Dante", "copies" : 2 },
{ "_id" : 8752, "title" : "Divine Comedy", "author" : "Dante", "copies" : 1 },
{ "_id" : 8645, "title" : "Eclogues", "author" : "Dante", "copies" : 2 },
{ "_id" : 7000, "title" : "The Odyssey", "author" : "Homer", "copies" : 10 },
{ "_id" : 7020, "title" : "Iliad", "author" : "Homer", "copies" : 10 }
])
根據(jù)作者對(duì)標(biāo)題分組
下面的聚合操作將books集合中的數(shù)據(jù)透視為按作者分組的標(biāo)題。
db.books.aggregate([
{ $group : { _id : "$author", books: { $push: "$title" } } }
])
結(jié)果
{ "_id" : "Homer", "books" : [ "The Odyssey", "Iliad" ] }
{ "_id" : "Dante", "books" : [ "The Banquet", "Divine Comedy", "Eclogues" ] }
根據(jù)作者對(duì)文檔分組
db.books.aggregate([
// 階段1
{
$group : { _id : "$author", books: { $push: "$$ROOT" } }
},
// 階段2
{
$addFields:
{
totalCopies : { $sum: "$books.copies" }
}
}
])
階段1:分組$group,根據(jù)作者對(duì)文檔進(jìn)行分組,使用$$ROOT把文檔作為books的元素。
階段2:$addFields會(huì)在輸出文檔中添加一個(gè)字段,即每位作者的圖書總印數(shù)。
結(jié)果:
{
"_id" : "Homer",
"books" :
[
{ "_id" : 7000, "title" : "The Odyssey", "author" : "Homer", "copies" : 10 },
{ "_id" : 7020, "title" : "Iliad", "author" : "Homer", "copies" : 10 }
],
"totalCopies" : 20
}{
"_id" : "Dante",
"books" :
[
{ "_id" : 8751, "title" : "The Banquet", "author" : "Dante", "copies" : 2 },
{ "_id" : 8752, "title" : "Divine Comedy", "author" : "Dante", "copies" : 1 },
{ "_id" : 8645, "title" : "Eclogues", "author" : "Dante", "copies" : 2 }
],
"totalCopies" : 5
}
以上內(nèi)容參考mongodb官方文檔整理而來(lái)
總結(jié)
到此這篇關(guān)于MongoDB數(shù)據(jù)庫(kù)聚合之分組統(tǒng)計(jì)$group的用法詳解的文章就介紹到這了,更多相關(guān)MongoDB分組統(tǒng)計(jì)$group用法內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解mongoDB主從復(fù)制搭建詳細(xì)過(guò)程
這篇文章主要介紹了詳解mongoDB主從復(fù)制搭建詳細(xì)過(guò)程的相關(guān)資料,這里對(duì)實(shí)現(xiàn)主從復(fù)制進(jìn)行了詳細(xì)的步驟介紹,需要的朋友可以參考下2017-08-08
MongoDB aggregate 運(yùn)用篇個(gè)人總結(jié)
最近一直在用mongodb,有時(shí)候會(huì)需要用到統(tǒng)計(jì),在網(wǎng)上查了一些資料,最適合用的就是用aggregate,以下介紹一下自己運(yùn)用的心得2016-11-11
2021最新版windows10系統(tǒng)MongoDB數(shù)據(jù)庫(kù)安裝及配置環(huán)境
這篇文章主要介紹了2021最新版MongoDB數(shù)據(jù)庫(kù)安裝及配置環(huán)境(windows10系統(tǒng)),本文通過(guò)圖文實(shí)例相結(jié)合給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-03-03
?PostgreSQL?與MongoDB使用對(duì)比分析
這篇文章主要介紹了為什么?PostgreSQL?能代替?MongoDB?,需要的朋友可以參考下2023-12-12

