기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.
$first
버전 5.0의 새 버전입니다.
Elastic 클러스터에서는 지원되지 않습니다.
Amazon DocumentDB의 $first 연산자는 그룹화된 문서 세트에서 첫 번째 문서를 반환합니다. 일반적으로 집계 파이프라인에서 특정 조건과 일치하는 첫 번째 문서를 검색하는 데 사용됩니다.
파라미터
예제(MongoDB 쉘)
다음 예제에서는 연$first산자를 사용하여 집계 중에 각 범주에 대해 발생한 첫 번째 항목 값을 검색하는 방법을 보여줍니다.
참고:는 파이프라인의 현재 문서 순서를 기반으로 첫 번째 문서를 $first 반환합니다. 특정 주문(예: 날짜, 가격 등)을 보장하려면 $sort 스테이지 전에 $group 스테이지를 사용해야 합니다.
샘플 문서 생성
db.products.insertMany([
{ _id: 1, item: "abc", price: 10, category: "food" },
{ _id: 2, item: "jkl", price: 20, category: "food" },
{ _id: 3, item: "xyz", price: 5, category: "toy" },
{ _id: 4, item: "abc", price: 5, category: "toy" }
]);
쿼리 예제
db.products.aggregate([
{ $group: { _id: "$category", firstItem: { $first: "$item" } } }
]);
출력
[
{ "_id" : "food", "firstItem" : "abc" },
{ "_id" : "toy", "firstItem" : "xyz" }
]
창 연산자 사용 예제(MongoDB Shell)
버전 8.0.2에서 새로 추가되었습니다.
연$first산자는 $setWindowFields 스테이지에서 창 연산자로 사용할 수도 있습니다. 이 컨텍스트에서는 각 창의 expression 첫 번째 문서에서의 값을 반환합니다. output 필드 아래에 연산자를 지정하고 선택적으로 window 문서로 창 경계를 정의합니다.
에서 창 연산자로 사용할 경우 $setWindowFields$first는 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: {
firstPrice: {
$first: "$price",
window: { documents: ["unbounded", "current"] }
}
}
}
}
]);
출력
[
{ "_id": 1, "ticker": "ABC", "hour": 1, "price": 50, "firstPrice": 50 },
{ "_id": 2, "ticker": "ABC", "hour": 2, "price": 45, "firstPrice": 50 },
{ "_id": 3, "ticker": "ABC", "hour": 3, "price": 60, "firstPrice": 50 },
{ "_id": 4, "ticker": "ABC", "hour": 4, "price": 40, "firstPrice": 50 },
{ "_id": 5, "ticker": "XYZ", "hour": 1, "price": 30, "firstPrice": 30 },
{ "_id": 6, "ticker": "XYZ", "hour": 2, "price": 35, "firstPrice": 30 },
{ "_id": 7, "ticker": "XYZ", "hour": 3, "price": 25, "firstPrice": 30 }
]
각 문서는 창의 첫 번째 문서(파티션에서 가장 빠른 문서)의 가격firstPrice인 hour로 보강됩니다.
코드 예제
$first 연산자 사용에 대한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다. 다음 예제에서는 누산기 사용량()과 창 연산자 사용량($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: first value per group
const products = db.collection('products');
await products.insertMany([
{ _id: 1, item: "abc", price: 10, category: "food" },
{ _id: 2, item: "jkl", price: 20, category: "food" },
{ _id: 3, item: "xyz", price: 5, category: "toy" },
{ _id: 4, item: "abc", price: 5, category: "toy" }
]);
const accumulatorResult = await products.aggregate([
{ $group: { _id: "$category", firstItem: { $first: "$item" } } }
]).toArray();
console.log('Accumulator result:', accumulatorResult);
// Window operator usage: first value within 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: {
firstPrice: {
$first: "$price",
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: first value per group
products = db['products']
products.insert_many([
{ '_id': 1, 'item': 'abc', 'price': 10, 'category': 'food' },
{ '_id': 2, 'item': 'jkl', 'price': 20, 'category': 'food' },
{ '_id': 3, 'item': 'xyz', 'price': 5, 'category': 'toy' },
{ '_id': 4, 'item': 'abc', 'price': 5, 'category': 'toy' }
])
accumulator_result = list(products.aggregate([
{ '$group': { '_id': '$category', 'firstItem': { '$first': '$item' } } }
]))
pprint(accumulator_result)
# Window operator usage: first value within 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': {
'firstPrice': {
'$first': '$price',
'window': { 'documents': ['unbounded', 'current'] }
}
}
}
}
]))
pprint(window_result)
except Exception as e:
print(f"An error occurred: {e}")
finally:
if client:
client.close()
example()