View a markdown version of this page

$firstN - Amazon DocumentDB

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

$firstN

버전 8.0.1에서 새로 추가되었습니다.

Amazon DocumentDB의 $firstN 연산자는 첫 번째 N 요소를 반환합니다. $group 스테이지에서 누적기로 사용할 경우 각 그룹의 첫 번째 N 값의 배열을 반환합니다. 배열 표현식 연산자로 사용할 경우 배열의 첫 번째 N 요소를 반환합니다.

파라미터

  • input: 값을 반환할 필드 또는 배열로 확인되는 표현식입니다.

  • n: 반환할 값의 수를 지정하는 양의 정수입니다. $group 스테이지에서 누적기로 사용되는 경우 그룹 _id 필드를 기반으로 양의 정수로 확인되는 한 도 표현식이 될 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"] } ]

코드 예제

$firstN 누적기 사용에 대한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다. 다음 예제에서는 누적기 사용량()과 표현식 사용량($group)을 모두 보여줍니다. $project

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'); 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'); const expressionResult = await inventory.aggregate([ { $project: { firstThreeTags: { $firstN: { input: "$tags", n: 3 } } } } ]).toArray(); console.log('Expression result:', expressionResult); } finally { await client.close(); } } example();
Python
from pymongo import MongoClient 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'] 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'] expression_result = list(inventory.aggregate([ { '$project': { 'firstThreeTags': { '$firstN': { 'input': '$tags', 'n': 3 } } } } ])) print('Expression result:', expression_result) finally: client.close() example()