$median累加運算子會計算一組文件中數值欄位的中位數值。
語法
{
$group: {
_id: < expression > ,
medianValue: {
$median: {
input: < field or expression > ,
method: < >
}
}
}
}
參數
| 參數 | Description |
|---|---|
<field or expression> |
要計算中位數的欄位或運算式。 |
範例
請參考商店集合中的此範例檔。
{
"_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:計算銷售量中位數
若要計算每個類別內的銷售量中位數,請先依不同的銷售類別將文件分組,然後計算每個分組類別內的銷售額中位數。
db.stores.aggregate([{
$unwind: "$sales.salesByCategory"
}, {
$group: {
_id: "$sales.salesByCategory.categoryName",
medianSales: {
$median: {
"input": "$sales.salesByCategory.totalSales",
"method": "approximate"
}
}
}
}])
此查詢傳回的前五個結果如下:
[
{
"_id": "Light Bulbs",
"medianSales": 24845
},
{
"_id": "Christmas Trees",
"medianSales": 28210
},
{
"_id": "Ukuleles",
"medianSales": 27295
},
{
"_id": "GPUs",
"medianSales": 19813
},
{
"_id": "Towels",
"medianSales": 27771
}
]