$last - Amazon DocumentDB

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

$last

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

参数

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

示例(MongoDB 外壳)

以下示例演示了如何将$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 } } ]

代码示例

要查看使用该$last命令的代码示例,请选择要使用的语言的选项卡:

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'); const collection = db.collection('collection'); const result = await collection.aggregate([ { $match: { name: "John" } }, { $project: { name: 1, lastScienceScore: { $last: { $filter: { input: "$scores", as: "score", cond: { $eq: ["$$score.subject", "science"] } } } } } } ]).toArray(); console.log(JSON.stringify(result, 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 collection = db.collection pipeline = [ { "$match": { "name": "John" } }, { "$project": { "name": 1, "lastScienceScore": { "$last": { "$filter": { "input": "$scores", "as": "score", "cond": { "$eq": ["$$score.subject", "science"] } } } } } } ] result = list(collection.aggregate(pipeline)) print(result) client.close() example()