$percentile演算子は、フィルター条件に一致する数値のパーセンタイルを計算します。 この演算子は、中央値や百分位数などの統計的しきい値を識別するのに特に役立ちます。
構文
$percentile: {
input: < field or expression > ,
p: [ < percentile values > ],
method: < method >
}
パラメーター
| パラメーター | Description |
|---|---|
input |
パーセンタイルを計算する数値データを指定します。 |
p |
計算するパーセンタイル値の配列 (0 ~ 1)。 |
method |
使用する補間方法を指定します。 有効値は "approximate" または "continuous" です。 |
例示
stores コレクションのこのサンプル ドキュメントについて考えてみましょう。
{
"_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: 売上高の 50 パーセンタイルを計算する
このクエリでは、すべての店舗の各販売カテゴリ内の総売上高の 50 パーセンタイル (中央値) が計算されます。
db.stores.aggregate([{
$unwind: "$sales.salesByCategory"
},
{
$group: {
_id: null,
medianSales: {
$percentile: {
input: "$sales.salesByCategory.totalSales",
p: [0.5],
method: "approximate"
}
}
}
}
])
このクエリは、次の結果を返します。
[
{
"_id": null,
"medianSales": [
25070.449624139295
]
}
]
例 2: 複数のパーセンタイルを計算する
このクエリでは、すべての店舗の売上合計の 25 パーセンタイル、50 パーセンタイル、および 75 パーセンタイルが計算されます。
db.stores.aggregate([{
$group: {
_id: null,
percentiles: {
$percentile: {
input: "$sales.fullSales",
p: [0.25, 0.5, 0.75],
method: "approximate"
}
}
}
}])
このクエリは、次の結果を返します。
[
{
"_id": null,
"percentiles": [
3700,
3700,
3700
]
}
]