翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。
$last
Amazon DocumentDB の $last演算子は、クエリ条件に一致する配列の最後の要素を返すために使用されます。これは、特定の条件を満たす配列の最新の要素または最後の要素を取得する場合に特に便利です。
パラメータ
-
expression: 配列要素に一致する式。
例 (MongoDB シェル)
次の例は、 演算子を $lastと組み合わせて使用$filterして、特定の条件を満たす配列から最後の要素を取得する方法を示しています (例: subject is '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 コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。