View a markdown version of this page

$last - Amazon DocumentDB

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

$last

Amazon DocumentDB 中的$last运算符用于返回数组中符合查询条件的最后一个元素。它对于检索数组中满足特定条件的最新或最后一个元素特别有用。

参数

  • expression: 匹配数组元素的表达式。

示例(MongoDB Shell)

以下示例演示如何将$last运算符与$filter结合使用,从满足特定条件(例如,主题是 “科学”)的数组中检索最后一个元素。

创建示例文档

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运算符的代码示例,请选择要使用的语言的选项卡。以下示例显示了表达式的用法 (in$project) 和窗口运算符的用法 (in$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()