기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.
$maxN
버전 8.0.1에서 새로 추가되었습니다.
Amazon DocumentDB의 $maxN 연산자는 N개의 가장 큰 값을 반환합니다. $group 스테이지에서 누적기로 사용할 경우 각 그룹의 N 최대값 배열을 반환합니다. 배열 표현식 연산자로 사용할 경우 배열의 N 최대 요소를 반환합니다.
파라미터
동작
배열 표현식 연산자 동작
-
보다 n 작은 값은 지정할 수 없습니다1.
-
$maxN는 input 배열에서 찾은 null 값을 필터링합니다.
-
지정된 n가 input 배열의 요소 수보다 크거나 같으면는 input 배열의 모든 요소를 $maxN 반환합니다.
-
가 배열이 아닌 값으로 input 확인되면 집계 작업 오류가 발생합니다.
-
에 숫자 및 문자열 요소가 모두 input 포함된 경우 문자열 요소는 BSON 비교 순서에 따라 숫자 요소 앞에 정렬됩니다.
누산기 동작
-
누적기로 사용되는 경우는 상수이거나의 _id 값에 따라 달라지는 양의 정수 표현식이어야 n 합니다$group.
-
$maxN는 null 및 누락 값을 필터링합니다.
-
그룹에 개 미만의 n 요소가 포함된 경우는 그룹의 모든 요소를 $maxN 반환합니다.
-
$maxN는 BSON 비교 순서에 따라 입력 데이터를 비교하여 적절한 출력 유형을 결정합니다. 입력 데이터에 여러 데이터 형식이 포함된 경우 $maxN 출력 형식은 비교 순서에서 가장 높습니다.
출력 순서 지정
$maxN는 특정 정렬 순서로 값을 반환하지 않습니다. 특정 정렬 순서를 보장해야 하는 경우 $topN 대신를 사용하거나 결과를 로 래핑합니다$sortArray.
예제(MongoDB 쉘)
다음 예제에서는 $maxN 누적기를 사용하여 각 주제에 대해 가장 높은 두 점수를 검색하는 방법을 보여줍니다.
샘플 문서 생성
db.scores.insertMany([
{ subject: "math", score: 85 },
{ subject: "math", score: 72 },
{ subject: "math", score: 93 },
{ subject: "math", score: 68 },
{ subject: "science", score: 90 },
{ subject: "science", score: 78 },
{ subject: "science", score: 65 },
{ subject: "science", score: 88 }
]);
쿼리 예제
db.scores.aggregate([
{ $group: { _id: "$subject", highestTwo: { $maxN: { input: "$score", n: 2 } } } }
]);
출력
[
{ "_id": "math", "highestTwo": [85, 93] },
{ "_id": "science", "highestTwo": [88, 90] }
]
표현식 사용 예제(MongoDB Shell)
연$maxN산자를 $project 단계 내의 표현식으로 사용하여 배열 필드에서 가장 큰 N 요소를 반환할 수도 있습니다.
샘플 문서 생성
db.readings.insertMany([
{ _id: 1, sensor: "A", values: [45, 12, 78, 3, 56] },
{ _id: 2, sensor: "B", values: [90, 23, 67, 11, 44] }
]);
쿼리 예제
db.readings.aggregate([
{ $project: {
highestThree: { $maxN: { input: "$values", n: 3 } }
}}
]);
출력
[
{ "_id": 1, "highestThree": [45, 56, 78] },
{ "_id": 2, "highestThree": [44, 90, 67] }
]
창 연산자 사용 예제(MongoDB Shell)
버전 8.0.2에서 새로 추가되었습니다.
연$maxN산자는 $setWindowFields 스테이지에서 창 연산자로도 사용할 수 있습니다. 이 컨텍스트에서는 각 창의 문서에 대해 최대 n 최대 값의 배열을 반환합니다. output 필드 아래에 연산자를 지정하고 선택적으로 window 문서로 창 경계를 정의합니다.
에서 창 연산자로 사용할 경우 $setWindowFields$maxN는 100MB의 중간 데이터로 제한됩니다. 이 제한을 초과하는 작업은 오류를 반환합니다.
샘플 문서 생성
db.stockPrices.insertMany([
{ _id: 1, ticker: "ABC", hour: 1, price: 50 },
{ _id: 2, ticker: "ABC", hour: 2, price: 45 },
{ _id: 3, ticker: "ABC", hour: 3, price: 60 },
{ _id: 4, ticker: "ABC", hour: 4, price: 40 },
{ _id: 5, ticker: "XYZ", hour: 1, price: 30 },
{ _id: 6, ticker: "XYZ", hour: 2, price: 35 },
{ _id: 7, ticker: "XYZ", hour: 3, price: 25 }
]);
쿼리 예제
다음 예제에서는 문서를 기준으로 분할하고ticker, 각 파티션을 기준으로 정렬하고hour, 파티션 시작부터 현재 문서까지 가장 높은 가격 2개를 반환합니다.
db.stockPrices.aggregate([
{
$setWindowFields: {
partitionBy: "$ticker",
sortBy: { hour: 1 },
output: {
highestTwoSoFar: {
$maxN: { input: "$price", n: 2 },
window: { documents: ["unbounded", "current"] }
}
}
}
}
]);
출력
[
{ "_id": 1, "ticker": "ABC", "hour": 1, "price": 50, "highestTwoSoFar": [50] },
{ "_id": 2, "ticker": "ABC", "hour": 2, "price": 45, "highestTwoSoFar": [50, 45] },
{ "_id": 3, "ticker": "ABC", "hour": 3, "price": 60, "highestTwoSoFar": [60, 50] },
{ "_id": 4, "ticker": "ABC", "hour": 4, "price": 40, "highestTwoSoFar": [60, 50] },
{ "_id": 5, "ticker": "XYZ", "hour": 1, "price": 30, "highestTwoSoFar": [30] },
{ "_id": 6, "ticker": "XYZ", "hour": 2, "price": 35, "highestTwoSoFar": [35, 30] },
{ "_id": 7, "ticker": "XYZ", "hour": 3, "price": 25, "highestTwoSoFar": [35, 30] }
]
각 문서는 창 내에서 가장 큰 두 price 값highestTwoSoFar인 로 보강됩니다. 출력 순서 섹션에 설명된 대로 반환된 배열 내의 값 순서는 보장되지 않습니다.
코드 예제
$maxN 연산자 사용에 대한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다. 다음 예제에서는 누적기 사용량(의 $group), 표현식 사용량(의 $project) 및 창 연산자 사용량(의 )을 보여줍니다. $setWindowFields
- Node.js
-
const { MongoClient } = require('mongodb');
async function example() {
const client = new MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
try {
await client.connect();
const db = client.db('test');
// Accumulator usage: N largest values per group
const scores = db.collection('scores');
await scores.insertMany([
{ subject: "math", score: 85 },
{ subject: "math", score: 72 },
{ subject: "math", score: 93 },
{ subject: "math", score: 68 },
{ subject: "science", score: 90 },
{ subject: "science", score: 78 },
{ subject: "science", score: 65 },
{ subject: "science", score: 88 }
]);
const accumulatorResult = await scores.aggregate([
{ $group: { _id: "$subject", highestTwo: { $maxN: { input: "$score", n: 2 } } } }
]).toArray();
console.log('Accumulator result:', accumulatorResult);
// Expression usage: N largest elements from an array field
const readings = db.collection('readings');
await readings.insertMany([
{ _id: 1, sensor: "A", values: [45, 12, 78, 3, 56] },
{ _id: 2, sensor: "B", values: [90, 23, 67, 11, 44] }
]);
const expressionResult = await readings.aggregate([
{ $project: { highestThree: { $maxN: { input: "$values", n: 3 } } } }
]).toArray();
console.log('Expression result:', expressionResult);
// Window operator usage: N largest values over a window in each partition
const stockPrices = db.collection('stockPrices');
await stockPrices.insertMany([
{ _id: 1, ticker: "ABC", hour: 1, price: 50 },
{ _id: 2, ticker: "ABC", hour: 2, price: 45 },
{ _id: 3, ticker: "ABC", hour: 3, price: 60 },
{ _id: 4, ticker: "ABC", hour: 4, price: 40 },
{ _id: 5, ticker: "XYZ", hour: 1, price: 30 },
{ _id: 6, ticker: "XYZ", hour: 2, price: 35 },
{ _id: 7, ticker: "XYZ", hour: 3, price: 25 }
]);
const windowResult = await stockPrices.aggregate([
{
$setWindowFields: {
partitionBy: "$ticker",
sortBy: { hour: 1 },
output: {
highestTwoSoFar: {
$maxN: { input: "$price", n: 2 },
window: { documents: ["unbounded", "current"] }
}
}
}
}
]).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: N largest values per group
scores = db['scores']
scores.insert_many([
{ 'subject': 'math', 'score': 85 },
{ 'subject': 'math', 'score': 72 },
{ 'subject': 'math', 'score': 93 },
{ 'subject': 'math', 'score': 68 },
{ 'subject': 'science', 'score': 90 },
{ 'subject': 'science', 'score': 78 },
{ 'subject': 'science', 'score': 65 },
{ 'subject': 'science', 'score': 88 }
])
accumulator_result = list(scores.aggregate([
{ '$group': { '_id': '$subject', 'highestTwo': { '$maxN': { 'input': '$score', 'n': 2 } } } }
]))
print('Accumulator result:', accumulator_result)
# Expression usage: N largest elements from an array field
readings = db['readings']
readings.insert_many([
{ '_id': 1, 'sensor': 'A', 'values': [45, 12, 78, 3, 56] },
{ '_id': 2, 'sensor': 'B', 'values': [90, 23, 67, 11, 44] }
])
expression_result = list(readings.aggregate([
{ '$project': { 'highestThree': { '$maxN': { 'input': '$values', 'n': 3 } } } }
]))
print('Expression result:', expression_result)
# Window operator usage: N largest values over a window in each partition
stock_prices = db['stockPrices']
stock_prices.insert_many([
{ '_id': 1, 'ticker': 'ABC', 'hour': 1, 'price': 50 },
{ '_id': 2, 'ticker': 'ABC', 'hour': 2, 'price': 45 },
{ '_id': 3, 'ticker': 'ABC', 'hour': 3, 'price': 60 },
{ '_id': 4, 'ticker': 'ABC', 'hour': 4, 'price': 40 },
{ '_id': 5, 'ticker': 'XYZ', 'hour': 1, 'price': 30 },
{ '_id': 6, 'ticker': 'XYZ', 'hour': 2, 'price': 35 },
{ '_id': 7, 'ticker': 'XYZ', 'hour': 3, 'price': 25 }
])
window_result = list(stock_prices.aggregate([
{
'$setWindowFields': {
'partitionBy': '$ticker',
'sortBy': { 'hour': 1 },
'output': {
'highestTwoSoFar': {
'$maxN': { 'input': '$price', 'n': 2 },
'window': { 'documents': ['unbounded', 'current'] }
}
}
}
}
]))
print('Window result:', window_result)
finally:
client.close()
example()