$group匯總階段會依指定的標識符表達式將檔分組,並套用累加器表達式來為每個群組建立計算欄位。 此階段對於數據匯總和摘要作業而言非常重要。
語法
{
$group: {
_id: <expression>,
<field1>: { <accumulator1>: <expression1> },
<field2>: { <accumulator2>: <expression2> }
}
}
參數
| 參數 | Description |
|---|---|
_id |
必須的。 要分組依據的表達式。 使用 null 計算所有輸入文件的累積值。 |
field |
選擇性。 使用累加器運算符計算,例如$sum、$avg、$max、$min、$count等。 |
範例
請參考商店集合中的此範例檔。
{
"_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f",
"name": "First Up Consultants | Bed and Bath Center - South Amir",
"location": {
"lat": 60.7954,
"lon": -142.0012
},
"staff": {
"totalStaff": {
"fullTime": 18,
"partTime": 17
}
},
"sales": {
"totalSales": 37701,
"salesByCategory": [
{
"categoryName": "Mattress Toppers",
"totalSales": 37701
}
]
},
"promotionEvents": [
{
"eventName": "Price Drop Palooza",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 9,
"Day": 21
},
"endDate": {
"Year": 2024,
"Month": 9,
"Day": 30
}
},
"discounts": [
{
"categoryName": "Bath Accessories",
"discountPercentage": 18
},
{
"categoryName": "Pillow Top Mattresses",
"discountPercentage": 17
}
]
}
]
}
範例 1:依城市劃分的群組人員配置分析
此查詢會依城市對商店進行分組,並分析不同位置的人員配置模式。
db.stores.aggregate([
{
$group: {
_id: "$city",
totalFullTimeStaff: { $sum: "$staff.employeeCount.fullTime" },
totalPartTimeStaff: { $sum: "$staff.employeeCount.partTime" },
avgFullTimeStaff: { $avg: "$staff.employeeCount.fullTime" },
storesInCity: { $count: {} }
}
},
{
$project: {
city: "$_id",
totalFullTimeStaff: 1,
totalPartTimeStaff: 1,
avgFullTimeStaff: { $round: ["$avgFullTimeStaff", 1] },
storesInCity: 1,
fullTimeRatio: {
$round: [
{ $divide: ["$totalFullTimeStaff", { $add: ["$totalFullTimeStaff", "$totalPartTimeStaff"] }] },
2
]
}
}
},
{ $limit : 2}
])
此查詢傳回的前兩個結果是:
[
{
"_id": "New Ellsworth",
"totalFullTimeStaff": 11,
"totalPartTimeStaff": 1,
"avgFullTimeStaff": 11,
"storesInCity": 1,
"city": "New Ellsworth",
"fullTimeRatio": 0.92
},
{
"_id": "Jalonborough",
"totalFullTimeStaff": 4,
"totalPartTimeStaff": 1,
"avgFullTimeStaff": 4,
"storesInCity": 1,
"city": "Jalonborough",
"fullTimeRatio": 0.8
}
]