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アキュムレータを使用して各項目の最初の 2 つの数量を取得する方法を示しています。

注記

$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 シェル)

$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 シェル)

バージョン 8.0.2 の新機能。

$firstN 演算子は、$setWindowFieldsステージのウィンドウ演算子としても使用できます。このコンテキストでは、各ウィンドウのドキュメントの最初のn値までの配列を返します。output フィールドで 演算子を指定し、オプションでwindowドキュメントを使用してウィンドウの境界を定義します。

注記

でウィンドウ演算子として使用する場合$setWindowFields、 $firstNは 100 MB の中間データに制限されます。この制限を超えるオペレーションはエラーを返します。

サンプルドキュメントを作成する

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、現在のドキュメントを通じてパーティションの先頭から見た最初の 2 つの料金を返します。

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、ウィンドウ内の最初の 2 つの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()