本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$last
Amazon DocumentDB 中的$last運算子用於傳回符合查詢條件之陣列中的最後一個元素。它特別適用於擷取陣列中符合特定條件的最新或最後一個元素。
參數
範例 (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 }
}
]
程式碼範例
若要檢視使用 $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()