本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$percentile
8.0.1 版的新功能。
Amazon DocumentDB 中的$percentile運算子會計算數值資料的指定百分位數值。做為累積器,它會在彙總管道$group階段的 群組內跨文件計算百分位數值。做為表達式,它會計算數字陣列的百分位數。
參數
-
input:解析為數值或數值陣列的表達式。
-
p:介於 0 和 1 之間的百分位數值陣列,其中每個值代表要計算的百分位數。例如, 會[0.25, 0.5, 0.75]計算第 25、第 50 和第 75 個百分位數。
-
method:指定計算方法的字串。目前僅支援 "approximate"。
Behavior (行為)
"approximate" 方法使用 t-digest 演算法來計算以百分位數為基礎的近似指標。使用小型資料集時,不同的百分位數值可能會解析為相同的結果。例如,每個群組只有 5 個值,p90 和 p99 可能會同時傳回群組中的最大值。精確度會隨著資料點數量的增加而提高。
範例 (MongoDB Shell)
下列範例顯示如何使用 $percentile 運算子計算每個類別分數的第 25 百分位數和第 75 百分位數。
建立範例文件
db.students.insertMany([
{ class: "A", score: 72 },
{ class: "A", score: 85 },
{ class: "A", score: 90 },
{ class: "A", score: 68 },
{ class: "A", score: 95 },
{ class: "B", score: 80 },
{ class: "B", score: 75 },
{ class: "B", score: 92 },
{ class: "B", score: 88 },
{ class: "B", score: 70 }
]);
查詢範例
db.students.aggregate([
{ $group: {
_id: "$class",
percentiles: { $percentile: { input: "$score", p: [0.25, 0.75], method: "approximate" } }
}}
]);
輸出
[
{ "_id": "A", "percentiles": [72, 90] },
{ "_id": "B", "percentiles": [75, 88] }
]
表達式用量範例 (MongoDB Shell)
$percentile 運算子也可以用作$project階段內的表達式,以計算陣列欄位的百分位數。
建立範例文件
db.surveys.insertMany([
{ _id: 1, responses: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] },
{ _id: 2, responses: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] }
]);
查詢範例
db.surveys.aggregate([
{ $project: {
quartiles: { $percentile: { input: "$responses", p: [0.25, 0.5, 0.75], method: "approximate" } }
}}
]);
輸出
[
{ "_id": 1, "quartiles": [6, 10, 16] },
{ "_id": 2, "quartiles": [5, 9, 15] }
]
視窗運算子用量範例 (MongoDB Shell)
8.0.2 版的新功能。
該$percentile運算子也可以用作$setWindowFields階段中的視窗運算子。在這種情況下,它會計算每個視窗中文件的指定百分位數值。您可以在 output 欄位下指定運算子,並選擇性地使用window文件定義視窗邊界。
在 中用作視窗運算子時$setWindowFields, 限制$percentile為 100 MB 的中繼資料。超過此限制的操作會傳回錯誤。
建立範例文件
db.sensorData.insertMany([
{ _id: 1, sensor: "A", reading: 72 },
{ _id: 2, sensor: "A", reading: 85 },
{ _id: 3, sensor: "A", reading: 90 },
{ _id: 4, sensor: "A", reading: 68 },
{ _id: 5, sensor: "A", reading: 95 },
{ _id: 6, sensor: "B", reading: 80 },
{ _id: 7, sensor: "B", reading: 75 },
{ _id: 8, sensor: "B", reading: 92 },
{ _id: 9, sensor: "B", reading: 88 },
{ _id: 10, sensor: "B", reading: 70 }
]);
查詢範例
下列範例會將文件分割為 ,sensor並計算每個分割區中reading所有文件的第 25 個百分位數和第 75 個百分位數。
db.sensorData.aggregate([
{
$setWindowFields: {
partitionBy: "$sensor",
output: {
readingPercentiles: {
$percentile: { input: "$reading", p: [0.25, 0.75], method: "approximate" },
window: { documents: ["unbounded", "unbounded"] }
}
}
}
}
]);
輸出
[
{ "_id": 1, "sensor": "A", "reading": 72, "readingPercentiles": [72, 90] },
{ "_id": 2, "sensor": "A", "reading": 85, "readingPercentiles": [72, 90] },
{ "_id": 3, "sensor": "A", "reading": 90, "readingPercentiles": [72, 90] },
{ "_id": 4, "sensor": "A", "reading": 68, "readingPercentiles": [72, 90] },
{ "_id": 5, "sensor": "A", "reading": 95, "readingPercentiles": [72, 90] },
{ "_id": 6, "sensor": "B", "reading": 80, "readingPercentiles": [75, 88] },
{ "_id": 7, "sensor": "B", "reading": 75, "readingPercentiles": [75, 88] },
{ "_id": 8, "sensor": "B", "reading": 92, "readingPercentiles": [75, 88] },
{ "_id": 9, "sensor": "B", "reading": 88, "readingPercentiles": [75, 88] },
{ "_id": 10, "sensor": "B", "reading": 70, "readingPercentiles": [75, 88] }
]
每個文件都會以 擴增readingPercentiles,也就是其分割區中reading所有文件的大約 25 個百分位數和 75 個百分位數。
程式碼範例
若要檢視使用 $percentile 運算子的程式碼範例,請選擇您要使用的語言標籤。下列範例顯示累積器用量 (在 中$group)、表達式用量 (在 中$project) 和視窗運算子用量 (在 中$setWindowFields):
- Node.js
-
const { MongoClient } = require('mongodb');
async function example() {
const uri = 'mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false';
const client = new MongoClient(uri);
try {
await client.connect();
const db = client.db('test');
// Accumulator usage: percentiles across grouped documents
const students = db.collection('students');
await students.insertMany([
{ class: "A", score: 72 },
{ class: "A", score: 85 },
{ class: "A", score: 90 },
{ class: "A", score: 68 },
{ class: "A", score: 95 },
{ class: "B", score: 80 },
{ class: "B", score: 75 },
{ class: "B", score: 92 },
{ class: "B", score: 88 },
{ class: "B", score: 70 }
]);
const accumulatorResult = await students.aggregate([
{ $group: {
_id: "$class",
percentiles: { $percentile: { input: "$score", p: [0.25, 0.75], method: "approximate" } }
}}
]).toArray();
console.log('Accumulator result:', accumulatorResult);
// Expression usage: percentiles of an array field
const surveys = db.collection('surveys');
await surveys.insertMany([
{ _id: 1, responses: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] },
{ _id: 2, responses: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] }
]);
const expressionResult = await surveys.aggregate([
{ $project: {
quartiles: { $percentile: { input: "$responses", p: [0.25, 0.5, 0.75], method: "approximate" } }
}}
]).toArray();
console.log('Expression result:', expressionResult);
// Window operator usage: percentiles across each partition
const sensorData = db.collection('sensorData');
await sensorData.insertMany([
{ _id: 1, sensor: "A", reading: 72 },
{ _id: 2, sensor: "A", reading: 85 },
{ _id: 3, sensor: "A", reading: 90 },
{ _id: 4, sensor: "A", reading: 68 },
{ _id: 5, sensor: "A", reading: 95 },
{ _id: 6, sensor: "B", reading: 80 },
{ _id: 7, sensor: "B", reading: 75 },
{ _id: 8, sensor: "B", reading: 92 },
{ _id: 9, sensor: "B", reading: 88 },
{ _id: 10, sensor: "B", reading: 70 }
]);
const windowResult = await sensorData.aggregate([
{
$setWindowFields: {
partitionBy: "$sensor",
output: {
readingPercentiles: {
$percentile: { input: "$reading", p: [0.25, 0.75], method: "approximate" },
window: { documents: ["unbounded", "unbounded"] }
}
}
}
}
]).toArray();
console.log('Window result:', windowResult);
} finally {
await client.close();
}
}
example();
- Python
-
from pymongo import MongoClient
def example():
client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
try:
db = client['test']
# Accumulator usage: percentiles across grouped documents
students = db['students']
students.insert_many([
{ 'class': 'A', 'score': 72 },
{ 'class': 'A', 'score': 85 },
{ 'class': 'A', 'score': 90 },
{ 'class': 'A', 'score': 68 },
{ 'class': 'A', 'score': 95 },
{ 'class': 'B', 'score': 80 },
{ 'class': 'B', 'score': 75 },
{ 'class': 'B', 'score': 92 },
{ 'class': 'B', 'score': 88 },
{ 'class': 'B', 'score': 70 }
])
accumulator_result = list(students.aggregate([
{ '$group': {
'_id': '$class',
'percentiles': { '$percentile': { 'input': '$score', 'p': [0.25, 0.75], 'method': 'approximate' } }
}}
]))
print('Accumulator result:', accumulator_result)
# Expression usage: percentiles of an array field
surveys = db['surveys']
surveys.insert_many([
{ '_id': 1, 'responses': [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] },
{ '_id': 2, 'responses': [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] }
])
expression_result = list(surveys.aggregate([
{ '$project': {
'quartiles': { '$percentile': { 'input': '$responses', 'p': [0.25, 0.5, 0.75], 'method': 'approximate' } }
}}
]))
print('Expression result:', expression_result)
# Window operator usage: percentiles across each partition
sensor_data = db['sensorData']
sensor_data.insert_many([
{ '_id': 1, 'sensor': 'A', 'reading': 72 },
{ '_id': 2, 'sensor': 'A', 'reading': 85 },
{ '_id': 3, 'sensor': 'A', 'reading': 90 },
{ '_id': 4, 'sensor': 'A', 'reading': 68 },
{ '_id': 5, 'sensor': 'A', 'reading': 95 },
{ '_id': 6, 'sensor': 'B', 'reading': 80 },
{ '_id': 7, 'sensor': 'B', 'reading': 75 },
{ '_id': 8, 'sensor': 'B', 'reading': 92 },
{ '_id': 9, 'sensor': 'B', 'reading': 88 },
{ '_id': 10, 'sensor': 'B', 'reading': 70 }
])
window_result = list(sensor_data.aggregate([
{
'$setWindowFields': {
'partitionBy': '$sensor',
'output': {
'readingPercentiles': {
'$percentile': { 'input': '$reading', 'p': [0.25, 0.75], 'method': 'approximate' },
'window': { 'documents': ['unbounded', 'unbounded'] }
}
}
}
}
]))
print('Window result:', window_result)
finally:
client.close()
example()