기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.
$bottomN
버전 8.0.1에서 새로 추가되었습니다.
$group 스테이지의 $bottomN 누적기를 사용하여 지정된 정렬 순서에 따라 그룹 내의 하단 N 요소를 반환합니다. 그룹에 N개 미만의 요소가 포함된 경우는 그룹의 모든 요소를 $bottomN 반환합니다.
파라미터
-
n: 그룹당 반환할 하위 결과 수를 지정하여 양수 또는 1로 확인되는 표현식입니다.
-
sortBy: 정렬 순서를 지정하는 문서입니다. 오름차순1에는를 사용하고 내림차순에는 -1를 사용합니다.
-
output: 각 하단 N개 문서에서 반환할 필드를 지정하는 표현식입니다.
예제(MongoDB 쉘)
다음 예제에서는 $bottomN 누적기를 사용하여 판매 컬렉션의 항목당 하위 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", bottomTwoSales: { $bottomN: { n: 2, sortBy: { quantity: -1 }, output: { quantity: "$quantity", price: "$price" } } } } }
])
출력
[
{ "_id": "xyz", "bottomTwoSales": [{ "quantity": 9, "price": 6 }, { "quantity": 3, "price": 12 }] },
{ "_id": "abc", "bottomTwoSales": [{ "quantity": 7, "price": 8 }, { "quantity": 5, "price": 10 }] }
]
코드 예제
$bottomN 연산자 사용에 대한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.
- 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", bottomTwoSales: { $bottomN: { n: 2, 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', 'bottomTwoSales': { '$bottomN': { 'n': 2, '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()