$group集計ステージは、指定された識別子式によってドキュメントをグループ化し、アキュムレータ式を適用して各グループの計算フィールドを作成します。 このステージは、データの集計と集計の操作に不可欠です。
構文
{
$group: {
_id: <expression>,
<field1>: { <accumulator1>: <expression1> },
<field2>: { <accumulator2>: <expression2> }
}
}
パラメーター
| パラメーター | Description |
|---|---|
_id |
必須。 グループ化する式。 すべての入力ドキュメントの累積値を計算するには、null を使用します。 |
field |
Optional. $sum、$avg、$max、$min、$countなどのアキュムレータ演算子を使用して計算されます。 |
例示
stores コレクションのこのサンプル ドキュメントについて考えてみましょう。
{
"_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}
])
このクエリによって返される最初の 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
}
]