기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.
$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" }
]
코드 예제
$first 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.
- 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('products');
const result = await collection.aggregate([
{ $group: { _id: "$category", firstItem: { $first: "$item" } } }
]).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['products']
result = list(collection.aggregate([
{ '$group': { '_id': '$category', 'firstItem': { '$first': '$item' } } }
]))
pprint(result)
except Exception as e:
print(f"An error occurred: {e}")
finally:
if client:
client.close()
example()