기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.
$firstN
버전 8.0.1에서 새로 추가되었습니다.
Amazon DocumentDB의 $firstN 연산자는 첫 번째 N 요소를 반환합니다. $group 스테이지에서 누적기로 사용할 경우 각 그룹의 첫 번째 N 값의 배열을 반환합니다. 배열 표현식 연산자로 사용할 경우 배열의 첫 번째 N 요소를 반환합니다.
파라미터
예제(MongoDB 쉘)
다음 예제에서는 집계 중에 $firstN 누적기를 사용하여 각 항목의 처음 두 수량을 검색하는 방법을 보여줍니다.
$firstN는 문서가 $group 단계에 도달하는 순서대로 값을 선택합니다. 특정 순서(예: 날짜 또는 점수)에 대한 첫 번째 N 값을 반환하려면 앞에 $sort 스테이지를 추가합니다$group.
샘플 문서 생성
db.sales.insertMany([
{ item: "abc", quantity: 10, date: ISODate("2023-01-01") },
{ item: "abc", quantity: 5, date: ISODate("2023-01-02") },
{ item: "abc", quantity: 8, date: ISODate("2023-01-03") },
{ item: "xyz", quantity: 15, date: ISODate("2023-01-01") },
{ item: "xyz", quantity: 7, date: ISODate("2023-01-02") },
{ item: "xyz", quantity: 3, date: ISODate("2023-01-03") }
]);
쿼리 예제
db.sales.aggregate([
{ $group: { _id: "$item", firstTwoQuantities: { $firstN: { input: "$quantity", n: 2 } } } }
]);
출력
[
{ "_id": "abc", "firstTwoQuantities": [10, 5] },
{ "_id": "xyz", "firstTwoQuantities": [15, 7] }
]
표현식 사용 예제(MongoDB Shell)
연$firstN산자를 $project 스테이지 내의 표현식으로 사용하여 배열 필드의 첫 번째 N 요소를 반환할 수도 있습니다.
샘플 문서 생성
db.inventory.insertMany([
{ _id: 1, item: "abc", tags: ["red", "green", "blue", "yellow", "purple"] },
{ _id: 2, item: "xyz", tags: ["alpha", "beta", "gamma"] }
]);
쿼리 예제
db.inventory.aggregate([
{ $project: {
firstThreeTags: { $firstN: { input: "$tags", n: 3 } }
}}
]);
출력
[
{ "_id": 1, "firstThreeTags": ["red", "green", "blue"] },
{ "_id": 2, "firstThreeTags": ["alpha", "beta", "gamma"] }
]
창 연산자 사용 예제(MongoDB Shell)
버전 8.0.2에서 새로 추가되었습니다.
연$firstN산자는 $setWindowFields 스테이지에서 창 연산자로 사용할 수도 있습니다. 이 컨텍스트에서는 각 창의 문서에 대해 최대 첫 번째 n 값의 배열을 반환합니다. output 필드 아래에 연산자를 지정하고 선택적으로 window 문서로 창 경계를 정의합니다.
에서 창 연산자로 사용할 경우 $setWindowFields$firstN는 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, 파티션 시작부터 현재 문서를 통해 표시되는 처음 두 가격을 반환합니다.
db.stockPrices.aggregate([
{
$setWindowFields: {
partitionBy: "$ticker",
sortBy: { hour: 1 },
output: {
firstTwoSoFar: {
$firstN: { input: "$price", n: 2 },
window: { documents: ["unbounded", "current"] }
}
}
}
}
]);
출력
[
{ "_id": 1, "ticker": "ABC", "hour": 1, "price": 50, "firstTwoSoFar": [50] },
{ "_id": 2, "ticker": "ABC", "hour": 2, "price": 45, "firstTwoSoFar": [50, 45] },
{ "_id": 3, "ticker": "ABC", "hour": 3, "price": 60, "firstTwoSoFar": [50, 45] },
{ "_id": 4, "ticker": "ABC", "hour": 4, "price": 40, "firstTwoSoFar": [50, 45] },
{ "_id": 5, "ticker": "XYZ", "hour": 1, "price": 30, "firstTwoSoFar": [30] },
{ "_id": 6, "ticker": "XYZ", "hour": 2, "price": 35, "firstTwoSoFar": [30, 35] },
{ "_id": 7, "ticker": "XYZ", "hour": 3, "price": 25, "firstTwoSoFar": [30, 35] }
]
각 문서는 창 내의 firstTwoSoFar처음 두 price 값(hour순서대로)인 로 보강됩니다.
코드 예제
$firstN 연산자 사용에 대한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다. 다음 예제에서는 누적기 사용량(의 $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: first N values per group
const sales = db.collection('sales');
await sales.insertMany([
{ item: "abc", quantity: 10, date: new Date("2023-01-01") },
{ item: "abc", quantity: 5, date: new Date("2023-01-02") },
{ item: "abc", quantity: 8, date: new Date("2023-01-03") },
{ item: "xyz", quantity: 15, date: new Date("2023-01-01") },
{ item: "xyz", quantity: 7, date: new Date("2023-01-02") },
{ item: "xyz", quantity: 3, date: new Date("2023-01-03") }
]);
const accumulatorResult = await sales.aggregate([
{ $group: { _id: "$item", firstTwoQuantities: { $firstN: { input: "$quantity", n: 2 } } } }
]).toArray();
console.log('Accumulator result:', accumulatorResult);
// Expression usage: first N elements of an array field
const inventory = db.collection('inventory');
await inventory.insertMany([
{ _id: 1, item: "abc", tags: ["red", "green", "blue", "yellow", "purple"] },
{ _id: 2, item: "xyz", tags: ["alpha", "beta", "gamma"] }
]);
const expressionResult = await inventory.aggregate([
{ $project: { firstThreeTags: { $firstN: { input: "$tags", n: 3 } } } }
]).toArray();
console.log('Expression result:', expressionResult);
// Window operator usage: first N 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: {
firstTwoSoFar: {
$firstN: { input: "$price", n: 2 },
window: { documents: ["unbounded", "current"] }
}
}
}
}
]).toArray();
console.log('Window result:', windowResult);
} finally {
await client.close();
}
}
example();
- Python
-
from pymongo import MongoClient
from datetime import datetime
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: first N values per group
sales = db['sales']
sales.insert_many([
{ 'item': 'abc', 'quantity': 10, 'date': datetime(2023, 1, 1) },
{ 'item': 'abc', 'quantity': 5, 'date': datetime(2023, 1, 2) },
{ 'item': 'abc', 'quantity': 8, 'date': datetime(2023, 1, 3) },
{ 'item': 'xyz', 'quantity': 15, 'date': datetime(2023, 1, 1) },
{ 'item': 'xyz', 'quantity': 7, 'date': datetime(2023, 1, 2) },
{ 'item': 'xyz', 'quantity': 3, 'date': datetime(2023, 1, 3) }
])
accumulator_result = list(sales.aggregate([
{ '$group': { '_id': '$item', 'firstTwoQuantities': { '$firstN': { 'input': '$quantity', 'n': 2 } } } }
]))
print('Accumulator result:', accumulator_result)
# Expression usage: first N elements of an array field
inventory = db['inventory']
inventory.insert_many([
{ '_id': 1, 'item': 'abc', 'tags': ['red', 'green', 'blue', 'yellow', 'purple'] },
{ '_id': 2, 'item': 'xyz', 'tags': ['alpha', 'beta', 'gamma'] }
])
expression_result = list(inventory.aggregate([
{ '$project': { 'firstThreeTags': { '$firstN': { 'input': '$tags', 'n': 3 } } } }
]))
print('Expression result:', expression_result)
# Window operator usage: first N 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': {
'firstTwoSoFar': {
'$firstN': { 'input': '$price', 'n': 2 },
'window': { 'documents': ['unbounded', 'current'] }
}
}
}
}
]))
print('Window result:', window_result)
finally:
client.close()
example()