기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.
$topN
버전 8.0.1에서 새로 추가되었습니다.
$group 스테이지의 $topN 누적기를 사용하여 지정된 정렬 순서에 따라 그룹 내의 상위 N개 요소를 반환합니다. 그룹에 N개 미만의 요소가 포함된 경우는 그룹의 모든 요소를 $topN 반환합니다.
파라미터
-
n: 그룹당 반환할 상위 결과 수를 지정하는 양의 정수 또는 1로 확인되는 표현식입니다.
-
sortBy: 정렬 순서를 지정하는 문서입니다. 오름차순1에는를 사용하고 내림차순에는 -1를 사용합니다.
-
output: 상위 N개 문서 각각에서 반환할 필드를 지정하는 표현식입니다.
예제(MongoDB 쉘)
다음 예제에서는 $topN 누적기를 사용하여 판매 컬렉션의 항목당 상위 2개 판매(최대 수량)를 찾는 방법을 보여줍니다.
샘플 문서 생성
db.sales.insertMany([
{ item: "abc", quantity: 10, price: 5 },
{ item: "abc", quantity: 7, price: 8 },
{ item: "abc", quantity: 5, price: 10 },
{ item: "xyz", quantity: 15, price: 3 },
{ item: "xyz", quantity: 9, price: 6 },
{ item: "xyz", quantity: 3, price: 12 }
])
쿼리 예제
db.sales.aggregate([
{ $group: { _id: "$item", topTwoSales: { $topN: { n: 2, sortBy: { quantity: -1 }, output: { quantity: "$quantity", price: "$price" } } } } }
])
출력
[
{ "_id": "xyz", "topTwoSales": [{ "quantity": 15, "price": 3 }, { "quantity": 9, "price": 6 }] },
{ "_id": "abc", "topTwoSales": [{ "quantity": 10, "price": 5 }, { "quantity": 7, "price": 8 }] }
]
창 연산자 사용 예제(MongoDB Shell)
버전 8.0.2에서 새로 추가되었습니다.
연$topN산자는 $setWindowFields 스테이지에서 창 연산자로 사용할 수도 있습니다. 이 컨텍스트에서는 각 창의 문서 중에서 상위 N개 문서(연산자 자신의에 따라sortBy)output의 배열을 반환합니다. output 필드 아래에 연산자를 지정하고 선택적으로 window 문서로 창 경계를 정의합니다.
에서 창 연산자로 사용할 경우 $setWindowFields$topN는 100MB의 중간 데이터로 제한됩니다. 이 제한을 초과하는 작업은 오류를 반환합니다.
샘플 문서 생성
db.matchScores.insertMany([
{ _id: 1, player: "Alice", round: 1, score: 20 },
{ _id: 2, player: "Alice", round: 2, score: 35 },
{ _id: 3, player: "Alice", round: 3, score: 28 },
{ _id: 4, player: "Bob", round: 1, score: 15 },
{ _id: 5, player: "Bob", round: 2, score: 40 }
]);
쿼리 예제
다음 예제에서는를 기준으로 문서를 분할하고player,를 기준으로 각 파티션을 정렬하고round, 파티션 시작부터 현재 문서를 통해 가장 높은 점수를 받은 두 라운드를 반환합니다.
db.matchScores.aggregate([
{
$setWindowFields: {
partitionBy: "$player",
sortBy: { round: 1 },
output: {
topTwoRoundsSoFar: {
$topN: { n: 2, sortBy: { score: -1 }, output: { round: "$round", score: "$score" } },
window: { documents: ["unbounded", "current"] }
}
}
}
}
]);
출력
[
{ "_id": 1, "player": "Alice", "round": 1, "score": 20, "topTwoRoundsSoFar": [{ "round": 1, "score": 20 }] },
{ "_id": 2, "player": "Alice", "round": 2, "score": 35, "topTwoRoundsSoFar": [{ "round": 2, "score": 35 }, { "round": 1, "score": 20 }] },
{ "_id": 3, "player": "Alice", "round": 3, "score": 28, "topTwoRoundsSoFar": [{ "round": 2, "score": 35 }, { "round": 3, "score": 28 }] },
{ "_id": 4, "player": "Bob", "round": 1, "score": 15, "topTwoRoundsSoFar": [{ "round": 1, "score": 15 }] },
{ "_id": 5, "player": "Bob", "round": 2, "score": 40, "topTwoRoundsSoFar": [{ "round": 2, "score": 40 }, { "round": 1, "score": 15 }] }
]
각 문서는 현재 문서를 포함하여 파티션 내에서 가장 높은 점수를 받은 topTwoRoundsSoFar두 라운드인 로 보강됩니다. 창에 문서가 2개 미만인 경우 모든 문서가 반환됩니다.
코드 예제
$topN 연산자 사용에 대한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다. 다음 예제에서는 누산기 사용량()과 창 연산자 사용량($group)을 모두 보여줍니다. $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: top N documents per group
const sales = db.collection('sales');
await sales.insertMany([
{ item: "abc", quantity: 10, price: 5 },
{ item: "abc", quantity: 7, price: 8 },
{ item: "abc", quantity: 5, price: 10 },
{ item: "xyz", quantity: 15, price: 3 },
{ item: "xyz", quantity: 9, price: 6 },
{ item: "xyz", quantity: 3, price: 12 }
]);
const accumulatorResult = await sales.aggregate([
{ $group: { _id: "$item", topTwoSales: { $topN: { n: 2, sortBy: { quantity: -1 }, output: { quantity: "$quantity", price: "$price" } } } } }
]).toArray();
console.log('Accumulator result:', accumulatorResult);
// Window operator usage: top two rounds so far within each partition
const matchScores = db.collection('matchScores');
await matchScores.insertMany([
{ _id: 1, player: "Alice", round: 1, score: 20 },
{ _id: 2, player: "Alice", round: 2, score: 35 },
{ _id: 3, player: "Alice", round: 3, score: 28 },
{ _id: 4, player: "Bob", round: 1, score: 15 },
{ _id: 5, player: "Bob", round: 2, score: 40 }
]);
const windowResult = await matchScores.aggregate([
{
$setWindowFields: {
partitionBy: "$player",
sortBy: { round: 1 },
output: {
topTwoRoundsSoFar: {
$topN: { n: 2, sortBy: { score: -1 }, output: { round: "$round", score: "$score" } },
window: { documents: ["unbounded", "current"] }
}
}
}
}
]).toArray();
console.log('Window result:', windowResult);
} catch (error) {
console.error('Error:', error);
} finally {
await client.close();
}
}
example();
- Python
-
from pymongo import MongoClient
from pprint import pprint
def example():
client = None
try:
client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client['test']
# Accumulator usage: top N documents per group
sales = db['sales']
sales.insert_many([
{ 'item': 'abc', 'quantity': 10, 'price': 5 },
{ 'item': 'abc', 'quantity': 7, 'price': 8 },
{ 'item': 'abc', 'quantity': 5, 'price': 10 },
{ 'item': 'xyz', 'quantity': 15, 'price': 3 },
{ 'item': 'xyz', 'quantity': 9, 'price': 6 },
{ 'item': 'xyz', 'quantity': 3, 'price': 12 }
])
accumulator_result = list(sales.aggregate([
{ '$group': { '_id': '$item', 'topTwoSales': { '$topN': { 'n': 2, 'sortBy': { 'quantity': -1 }, 'output': { 'quantity': '$quantity', 'price': '$price' } } } } }
]))
pprint(accumulator_result)
# Window operator usage: top two rounds so far within each partition
match_scores = db['matchScores']
match_scores.insert_many([
{ '_id': 1, 'player': 'Alice', 'round': 1, 'score': 20 },
{ '_id': 2, 'player': 'Alice', 'round': 2, 'score': 35 },
{ '_id': 3, 'player': 'Alice', 'round': 3, 'score': 28 },
{ '_id': 4, 'player': 'Bob', 'round': 1, 'score': 15 },
{ '_id': 5, 'player': 'Bob', 'round': 2, 'score': 40 }
])
window_result = list(match_scores.aggregate([
{
'$setWindowFields': {
'partitionBy': '$player',
'sortBy': { 'round': 1 },
'output': {
'topTwoRoundsSoFar': {
'$topN': { 'n': 2, 'sortBy': { 'score': -1 }, 'output': { 'round': '$round', 'score': '$score' } },
'window': { 'documents': ['unbounded', 'current'] }
}
}
}
}
]))
pprint(window_result)
except Exception as e:
print(f"An error occurred: {e}")
finally:
if client:
client.close()
example()