View a markdown version of this page

$lastN - Amazon DocumentDB

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

$lastN

8.0.1 版的新功能。

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

參數

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

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

範例 (MongoDB Shell)

下列範例示範如何在彙總期間使用$lastN累積器擷取每個項目的最後兩個數量。

注意

$lastN 會依文件到達$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", lastTwoQuantities: { $lastN: { input: "$quantity", n: 2 } } } } ]);

輸出

[ { "_id": "abc", "lastTwoQuantities": [5, 8] }, { "_id": "xyz", "lastTwoQuantities": [7, 3] } ]

表達式用量範例 (MongoDB Shell)

運算$lastN子也可以用作$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: { lastThreeTags: { $lastN: { input: "$tags", n: 3 } } }} ]);

輸出

[ { "_id": 1, "lastThreeTags": ["blue", "yellow", "purple"] }, { "_id": 2, "lastThreeTags": ["alpha", "beta", "gamma"] } ]

程式碼範例

若要檢視使用$lastN累積器的程式碼範例,請選擇您要使用的語言標籤。下列範例顯示累積器用量 (在 中$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: last N values per group const sales = db.collection('sales'); const accumulatorResult = await sales.aggregate([ { $group: { _id: "$item", lastTwoQuantities: { $lastN: { input: "$quantity", n: 2 } } } } ]).toArray(); console.log('Accumulator result:', accumulatorResult); // Expression usage: last N elements of an array field const inventory = db.collection('inventory'); const expressionResult = await inventory.aggregate([ { $project: { lastThreeTags: { $lastN: { 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: last N values per group sales = db['sales'] accumulator_result = list(sales.aggregate([ { '$group': { '_id': '$item', 'lastTwoQuantities': { '$lastN': { 'input': '$quantity', 'n': 2 } } } } ])) print('Accumulator result:', accumulator_result) # Expression usage: last N elements of an array field inventory = db['inventory'] expression_result = list(inventory.aggregate([ { '$project': { 'lastThreeTags': { '$lastN': { 'input': '$tags', 'n': 3 } } } } ])) print('Expression result:', expression_result) finally: client.close() example()