기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.
$상위
버전 8.0.1에서 새로 추가되었습니다.
$group 단계의 $top 누적기를 사용하여 지정된 정렬 순서에 따라 그룹당 가장 높은 순위의 문서를 반환합니다.
파라미터
예제(MongoDB 쉘)
다음 예제에서는 $top 누적기를 사용하여 판매 컬렉션의 항목당 최고 판매량(최고 수량)을 찾는 방법을 보여줍니다.
샘플 문서 생성
db.sales.insertMany([
{ item: "abc", quantity: 10, price: 5 },
{ item: "abc", quantity: 5, price: 8 },
{ item: "xyz", quantity: 15, price: 3 },
{ item: "xyz", quantity: 7, price: 6 }
])
쿼리 예제
db.sales.aggregate([
{ $group: { _id: "$item", topSale: { $top: { sortBy: { quantity: -1 }, output: { quantity: "$quantity", price: "$price" } } } } }
])
출력
[
{ "_id": "xyz", "topSale": { "quantity": 15, "price": 3 } },
{ "_id": "abc", "topSale": { "quantity": 10, "price": 5 } }
]
코드 예제
$top 연산자 사용에 대한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.
- 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');
const collection = db.collection('sales');
const result = await collection.aggregate([
{ $group: { _id: "$item", topSale: { $top: { sortBy: { quantity: -1 }, output: { quantity: "$quantity", price: "$price" } } } } }
]).toArray();
console.log(result);
} 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']
collection = db['sales']
result = list(collection.aggregate([
{ '$group': { '_id': '$item', 'topSale': { '$top': { 'sortBy': { 'quantity': -1 }, 'output': { 'quantity': '$quantity', 'price': '$price' } } } } }
]))
pprint(result)
except Exception as e:
print(f"An error occurred: {e}")
finally:
if client:
client.close()
example()