彙總管線中的 $bucket 階段會根據指定的界限,將輸入文件分組為貯體。 這對於建立直方圖或將數據分類為範圍特別有用。 它可讓您定義自定義桶界限,並提供彙總這些範圍內的數據的方式。
語法
{
$bucket: {
groupBy: <expression>,
boundaries: [ <lowerBoundary>, <upperBoundary>, ... ],
default: <defaultBucket>,
output: {
<outputField1>: { <accumulator1> },
...
}
}
}
參數
| 參數 | Description |
|---|---|
groupBy |
用來分組文件的表達式。 |
boundaries |
定義儲存桶界限值的陣列。 陣列必須以遞增順序排序,並包含至少兩個值。 |
default |
不在指定界限內文件的貯體名稱。 |
output |
指定每個貯體之計算欄位的選擇性欄位。 |
範例
請參考商店集合中的此範例檔。
{
"_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
"name": "First Up Consultants | Beverage Shop - Satterfieldmouth",
"location": {
"lat": -89.2384,
"lon": -46.4012
},
"staff": {
"totalStaff": {
"fullTime": 8,
"partTime": 20
}
},
"sales": {
"totalSales": 75670,
"salesByCategory": [
{
"categoryName": "Wine Accessories",
"totalSales": 34440
},
{
"categoryName": "Bitters",
"totalSales": 39496
},
{
"categoryName": "Rum",
"totalSales": 1734
}
]
},
"promotionEvents": [
{
"eventName": "Unbeatable Bargain Bash",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 6,
"Day": 23
},
"endDate": {
"Year": 2024,
"Month": 7,
"Day": 2
}
},
"discounts": [
{
"categoryName": "Whiskey",
"discountPercentage": 7
},
{
"categoryName": "Bitters",
"discountPercentage": 15
},
{
"categoryName": "Brandy",
"discountPercentage": 8
},
{
"categoryName": "Sports Drinks",
"discountPercentage": 22
},
{
"categoryName": "Vodka",
"discountPercentage": 19
}
]
},
{
"eventName": "Steal of a Deal Days",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 9,
"Day": 21
},
"endDate": {
"Year": 2024,
"Month": 9,
"Day": 29
}
},
"discounts": [
{
"categoryName": "Organic Wine",
"discountPercentage": 19
},
{
"categoryName": "White Wine",
"discountPercentage": 20
},
{
"categoryName": "Sparkling Wine",
"discountPercentage": 19
},
{
"categoryName": "Whiskey",
"discountPercentage": 17
},
{
"categoryName": "Vodka",
"discountPercentage": 23
}
]
}
]
}
範例 1:將 fullSales 分類至範圍
此查詢會 fullSales 將欄位分類為三個儲存區: [0, 1000)、 [1000, 5000)和 [5000, 10000)。 不屬於這些範圍的文件會分組為預設桶。
db.stores.aggregate([
{
$bucket: {
groupBy: "$sales.fullSales",
boundaries: [0, 1000, 5000, 10000],
default: "Other",
output: {
count: { $sum: 1 },
totalSales: { $sum: "$sales.fullSales" }
}
}
}
])
此查詢會傳回下列結果:
[
{ "_id": 1000, "count": 1, "totalSales": 3700 },
{ "_id": "Other", "count": 41504, "totalSales": 0 }
]