View a markdown version of this page

$last - Amazon DocumentDB

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

$last

Amazon DocumentDB 中的$last運算子用於傳回符合查詢條件之陣列中的最後一個元素。它特別適用於擷取陣列中符合特定條件的最新或最後一個元素。

參數

  • expression:符合陣列元素的表達式。

範例 (MongoDB Shell)

下列範例示範使用 $last運算子搭配 $filter,從符合特定條件的陣列擷取最後一個元素 (例如,主體是 'science')。

建立範例文件

db.collection.insertMany([ { "_id": 1, "name": "John", "scores": [ { "subject": "math", "score": 82 }, { "subject": "english", "score": 85 }, { "subject": "science", "score": 90 } ] }, { "_id": 2, "name": "Jane", "scores": [ { "subject": "math", "score": 92 }, { "subject": "english", "score": 88 }, { "subject": "science", "score": 87 } ] }, { "_id": 3, "name": "Bob", "scores": [ { "subject": "math", "score": 75 }, { "subject": "english", "score": 80 }, { "subject": "science", "score": 85 } ] } ]);

查詢範例

db.collection.aggregate([ { $match: { name: "John" } }, { $project: { name: 1, lastScienceScore: { $last: { $filter: { input: "$scores", as: "score", cond: { $eq: ["$$score.subject", "science"] } } } } } } ]);

輸出

[ { _id: 1, name: 'John', lastScienceScore: { subject: 'science', score: 90 } } ]

視窗運算子用量範例 (MongoDB Shell)

8.0.2 版的新功能。

該$last運算子也可以用作$setWindowFields階段中的視窗運算子。在這種情況下,它會傳回每個視窗中expression最後一個文件的 值。您可以在 output 欄位下指定運算子,並選擇性地使用window文件定義視窗邊界。

建立範例文件

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: { lastPrice: { $last: "$price", window: { documents: ["unbounded", "unbounded"] } } } } } ]);

輸出

[ { "_id": 1, "ticker": "ABC", "hour": 1, "price": 50, "lastPrice": 40 }, { "_id": 2, "ticker": "ABC", "hour": 2, "price": 45, "lastPrice": 40 }, { "_id": 3, "ticker": "ABC", "hour": 3, "price": 60, "lastPrice": 40 }, { "_id": 4, "ticker": "ABC", "hour": 4, "price": 40, "lastPrice": 40 }, { "_id": 5, "ticker": "XYZ", "hour": 1, "price": 30, "lastPrice": 25 }, { "_id": 6, "ticker": "XYZ", "hour": 2, "price": 35, "lastPrice": 25 }, { "_id": 7, "ticker": "XYZ", "hour": 3, "price": 25, "lastPrice": 25 } ]

每個文件都會以 擴增lastPrice,這是其視窗中最後一個文件的價格 (分割區hour中的最新 )。

程式碼範例

若要檢視使用 $last 運算子的程式碼範例,請選擇您要使用的語言標籤。下列範例顯示表達式用量 (在 中$project) 和視窗運算子用量 (在 中$setWindowFields):

Node.js
const { MongoClient } = require('mongodb'); async function example() { const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false'); const db = client.db('test'); // Expression usage: last element of a filtered array const collection = db.collection('collection'); await collection.insertMany([ { _id: 1, name: "John", scores: [ { subject: "math", score: 82 }, { subject: "english", score: 85 }, { subject: "science", score: 90 } ] }, { _id: 2, name: "Jane", scores: [ { subject: "math", score: 92 }, { subject: "english", score: 88 }, { subject: "science", score: 87 } ] }, { _id: 3, name: "Bob", scores: [ { subject: "math", score: 75 }, { subject: "english", score: 80 }, { subject: "science", score: 85 } ] } ]); const expressionResult = await collection.aggregate([ { $match: { name: "John" } }, { $project: { name: 1, lastScienceScore: { $last: { $filter: { input: "$scores", as: "score", cond: { $eq: ["$$score.subject", "science"] } } } } } } ]).toArray(); console.log('Expression result:', JSON.stringify(expressionResult, null, 2)); // Window operator usage: last value within 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: { lastPrice: { $last: "$price", window: { documents: ["unbounded", "unbounded"] } } } } } ]).toArray(); console.log('Window result:', JSON.stringify(windowResult, null, 2)); 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') db = client.test # Expression usage: last element of a filtered array collection = db.collection collection.insert_many([ { "_id": 1, "name": "John", "scores": [ { "subject": "math", "score": 82 }, { "subject": "english", "score": 85 }, { "subject": "science", "score": 90 } ] }, { "_id": 2, "name": "Jane", "scores": [ { "subject": "math", "score": 92 }, { "subject": "english", "score": 88 }, { "subject": "science", "score": 87 } ] }, { "_id": 3, "name": "Bob", "scores": [ { "subject": "math", "score": 75 }, { "subject": "english", "score": 80 }, { "subject": "science", "score": 85 } ] } ]) expression_pipeline = [ { "$match": { "name": "John" } }, { "$project": { "name": 1, "lastScienceScore": { "$last": { "$filter": { "input": "$scores", "as": "score", "cond": { "$eq": ["$$score.subject", "science"] } } } } } } ] expression_result = list(collection.aggregate(expression_pipeline)) print('Expression result:', expression_result) # Window operator usage: last value within 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_pipeline = [ { "$setWindowFields": { "partitionBy": "$ticker", "sortBy": { "hour": 1 }, "output": { "lastPrice": { "$last": "$price", "window": { "documents": ["unbounded", "unbounded"] } } } } } ] window_result = list(stock_prices.aggregate(window_pipeline)) print('Window result:', window_result) client.close() example()