翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。
$last
Amazon DocumentDB の $last演算子は、クエリ条件に一致する配列の最後の要素を返すために使用されます。これは、特定の条件を満たす配列の最新の要素または最後の要素を取得する場合に特に便利です。
パラメータ
例 (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 }
}
]
ウィンドウ演算子の使用例 (MongoDB シェル)
バージョン 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()