기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.
$백분위수
버전 8.0.1에서 새로 추가되었습니다.
Amazon DocumentDB의 $percentile 연산자는 숫자 데이터에 대해 지정된 백분위수 값을 계산합니다. 누적기는 집계 파이프라인의 $group 단계에서 그룹 내 문서 전반의 백분위수 값을 계산합니다. 표현식으로 숫자 배열의 백분위수를 계산합니다.
파라미터
-
input: 숫자 값 또는 숫자 값 배열로 확인되는 표현식입니다.
-
p: 0과 1 사이의 백분위수 값 배열로, 여기서 각 값은 계산할 백분위수를 나타냅니다. 예를 들어는 25번째, 50번째 및 75번째 백분위수를 [0.25, 0.5, 0.75] 계산합니다.
-
method: 계산 방법을 지정하는 문자열입니다. 현재 "approximate"만 지원됩니다.
동작
"approximate" 메서드는 t-digest 알고리즘을 사용하여 대략적인 백분위수 기반 지표를 계산합니다. 데이터 세트가 작으면 고유한 백분위수 값이 동일한 결과로 확인될 수 있습니다. 예를 들어 그룹당 값이 5개뿐인 경우 p90과 p99는 모두 그룹의 최대값을 반환할 수 있습니다. 데이터 포인트 수가 증가함에 따라 정밀도가 향상됩니다.
예제(MongoDB 쉘)
다음 예제에서는 $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는 100MB의 중간 데이터로 제한됩니다. 이 제한을 초과하는 작업은 오류를 반환합니다.
샘플 문서 생성
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()