기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.
버전 8.0.1에서 새로 추가되었습니다.
Amazon DocumentDB의 $median 연산자는 숫자 데이터의 중앙값을 계산합니다. 누적기는 집계 파이프라인의 $group 단계에서 그룹 내 문서 전반의 숫자 값 중앙값을 계산합니다. 표현식으로 숫자 배열의 중앙값을 계산합니다.
파라미터
"approximate" 메서드는 t-digest 알고리즘을 사용하여 대략적인 중앙값을 계산합니다. 결과는 값 간의 보간이 아닌 데이터 세트의 기존 값입니다. 데이터 포인트 수가 증가함에 따라 정밀도가 향상됩니다.
다음 예제에서는 $median 연산자를 사용하여 클래스당 테스트 점수 중앙값을 계산하는 방법을 보여줍니다.
샘플 문서 생성
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",
medianScore: { $median: { input: "$score", method: "approximate" } }
}}
]);
출력
[
{ "_id": "A", "medianScore": 85 },
{ "_id": "B", "medianScore": 80 }
]
연$median산자를 $project 단계 내의 표현식으로 사용하여 배열 필드의 중앙값을 계산할 수도 있습니다.
샘플 문서 생성
db.surveys.insertMany([
{ _id: 1, ratings: [3, 5, 7, 9, 2] },
{ _id: 2, ratings: [10, 20, 30, 40, 50] },
{ _id: 3, ratings: [1, 1, 2, 3, 5] }
]);
쿼리 예제
db.surveys.aggregate([
{ $project: {
medianRating: { $median: { input: "$ratings", method: "approximate" } }
}}
]);
출력
[
{ "_id": 1, "medianRating": 5 },
{ "_id": 2, "medianRating": 30 },
{ "_id": 3, "medianRating": 2 }
]
버전 8.0.2에서 새로 추가되었습니다.
연$median산자를 $setWindowFields 단계에서 창 연산자로 사용할 수도 있습니다. 이 컨텍스트에서는 각 창의 문서에 대한 숫자 값의 중앙값을 계산합니다. output 필드 아래에 연산자를 지정하고 선택적으로 window 문서로 창 경계를 정의합니다.
에서 창 연산자로 사용할 경우 $setWindowFields$median는 100MB의 중간 데이터로 제한됩니다. 이 제한을 초과하는 작업은 오류를 반환합니다.
샘플 문서 생성
db.temperatures.insertMany([
{ _id: 1, city: "A", reading: 60 },
{ _id: 2, city: "A", reading: 65 },
{ _id: 3, city: "A", reading: 70 },
{ _id: 4, city: "B", reading: 80 },
{ _id: 5, city: "B", reading: 85 },
{ _id: 6, city: "B", reading: 90 }
]);
쿼리 예제
다음 예시에서는 문서를 기준으로 분할city하고 각 파티션의 모든 문서에 reading 대한 중앙값을 계산합니다.
db.temperatures.aggregate([
{
$setWindowFields: {
partitionBy: "$city",
output: {
medianReading: {
$median: { input: "$reading", method: "approximate" },
window: { documents: ["unbounded", "unbounded"] }
}
}
}
}
]);
출력
[
{ "_id": 1, "city": "A", "reading": 60, "medianReading": 65 },
{ "_id": 2, "city": "A", "reading": 65, "medianReading": 65 },
{ "_id": 3, "city": "A", "reading": 70, "medianReading": 65 },
{ "_id": 4, "city": "B", "reading": 80, "medianReading": 85 },
{ "_id": 5, "city": "B", "reading": 85, "medianReading": 85 },
{ "_id": 6, "city": "B", "reading": 90, "medianReading": 85 }
]
각 문서는 파티션에 있는 reading 모든 문서의 대략적인 중앙값medianReading인 로 보강됩니다.
$median 연산자 사용에 대한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다. 다음 예제에서는 누적기 사용량(의 $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: median 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",
medianScore: { $median: { input: "$score", method: "approximate" } }
}}
]).toArray();
console.log('Accumulator result:', accumulatorResult);
// Expression usage: median of an array field
const surveys = db.collection('surveys');
await surveys.insertMany([
{ _id: 1, ratings: [3, 5, 7, 9, 2] },
{ _id: 2, ratings: [10, 20, 30, 40, 50] },
{ _id: 3, ratings: [1, 1, 2, 3, 5] }
]);
const expressionResult = await surveys.aggregate([
{ $project: {
medianRating: { $median: { input: "$ratings", method: "approximate" } }
}}
]).toArray();
console.log('Expression result:', expressionResult);
// Window operator usage: median across each partition
const temperatures = db.collection('temperatures');
await temperatures.insertMany([
{ _id: 1, city: "A", reading: 60 },
{ _id: 2, city: "A", reading: 65 },
{ _id: 3, city: "A", reading: 70 },
{ _id: 4, city: "B", reading: 80 },
{ _id: 5, city: "B", reading: 85 },
{ _id: 6, city: "B", reading: 90 }
]);
const windowResult = await temperatures.aggregate([
{
$setWindowFields: {
partitionBy: "$city",
output: {
medianReading: {
$median: { input: "$reading", 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: median 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',
'medianScore': { '$median': { 'input': '$score', 'method': 'approximate' } }
}}
]))
print('Accumulator result:', accumulator_result)
# Expression usage: median of an array field
surveys = db['surveys']
surveys.insert_many([
{ '_id': 1, 'ratings': [3, 5, 7, 9, 2] },
{ '_id': 2, 'ratings': [10, 20, 30, 40, 50] },
{ '_id': 3, 'ratings': [1, 1, 2, 3, 5] }
])
expression_result = list(surveys.aggregate([
{ '$project': {
'medianRating': { '$median': { 'input': '$ratings', 'method': 'approximate' } }
}}
]))
print('Expression result:', expression_result)
# Window operator usage: median across each partition
temperatures = db['temperatures']
temperatures.insert_many([
{ '_id': 1, 'city': 'A', 'reading': 60 },
{ '_id': 2, 'city': 'A', 'reading': 65 },
{ '_id': 3, 'city': 'A', 'reading': 70 },
{ '_id': 4, 'city': 'B', 'reading': 80 },
{ '_id': 5, 'city': 'B', 'reading': 85 },
{ '_id': 6, 'city': 'B', 'reading': 90 }
])
window_result = list(temperatures.aggregate([
{
'$setWindowFields': {
'partitionBy': '$city',
'output': {
'medianReading': {
'$median': { 'input': '$reading', 'method': 'approximate' },
'window': { 'documents': ['unbounded', 'unbounded'] }
}
}
}
}
]))
print('Window result:', window_result)
finally:
client.close()
example()