View a markdown version of this page

$firstN - Amazon DocumentDB

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

$firstN

8.0.1 版的新功能。

Amazon DocumentDB 中的$firstN運算子會傳回前 N 個元素。在$group階段中用作累積器時,它會傳回每個群組中第一個 N 值的陣列。用作陣列表達式運算子時,它會傳回陣列的第一個 N 元素。

參數

  • input:解析為要傳回值之欄位或陣列的表達式。

  • n:正整數,指定要傳回多少值。在$group階段中用作累積器時,n也可以是表達式,只要它根據群組_id欄位解析為正整數即可。

範例 (MongoDB Shell)

下列範例顯示如何在彙總期間使用$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為 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,並傳回從分割區開始到目前文件期間看到的前兩個價格。

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()