$last演算子は、クエリで指定された 1 つ以上のフィールドのドキュメントを並べ替え、フィルター条件に一致する最後のドキュメントを返します。
構文
{
"$last": <expression>
}
パラメーター
| パラメーター | Description |
|---|---|
expression |
結果セットから最後のドキュメントを評価して返す式 |
例示
stores コレクションのこのサンプル ドキュメントについて考えてみましょう。
{
"_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
"name": "First Up Consultants | Beverage Shop - Satterfieldmouth",
"location": {
"lat": -89.2384,
"lon": -46.4012
},
"staff": {
"totalStaff": {
"fullTime": 8,
"partTime": 20
}
},
"sales": {
"totalSales": 75670,
"salesByCategory": [
{
"categoryName": "Wine Accessories",
"totalSales": 34440
},
{
"categoryName": "Bitters",
"totalSales": 39496
},
{
"categoryName": "Rum",
"totalSales": 1734
}
]
},
"promotionEvents": [
{
"eventName": "Unbeatable Bargain Bash",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 6,
"Day": 23
},
"endDate": {
"Year": 2024,
"Month": 7,
"Day": 2
}
},
"discounts": [
{
"categoryName": "Whiskey",
"discountPercentage": 7
},
{
"categoryName": "Bitters",
"discountPercentage": 15
},
{
"categoryName": "Brandy",
"discountPercentage": 8
},
{
"categoryName": "Sports Drinks",
"discountPercentage": 22
},
{
"categoryName": "Vodka",
"discountPercentage": 19
}
]
},
{
"eventName": "Steal of a Deal Days",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 9,
"Day": 21
},
"endDate": {
"Year": 2024,
"Month": 9,
"Day": 29
}
},
"discounts": [
{
"categoryName": "Organic Wine",
"discountPercentage": 19
},
{
"categoryName": "White Wine",
"discountPercentage": 20
},
{
"categoryName": "Sparkling Wine",
"discountPercentage": 19
},
{
"categoryName": "Whiskey",
"discountPercentage": 17
},
{
"categoryName": "Vodka",
"discountPercentage": 23
}
]
}
]
}
例 1: 会社内で最後に更新されたストアを取得する
First Up Consultants 企業内で最近更新されたストアを取得するには、クエリを実行して First Up Consultants 内のすべてのストアをフェッチし、lastUpdated フィールドの昇順でドキュメントを並べ替え、並べ替えられた結果から最後のドキュメントを返します。
db.stores.aggregate([{
$match: {
company: {
$in: ["First Up Consultants"]
}
}
}, {
$sort: {
lastUpdated: 1
}
}, {
$group: {
_id: "$company",
lastUpdated: {
$last: "$lastUpdated"
}
}
}])
このクエリは、次の結果を返します。
[
{
"_id": "First Up Consultants",
"lastUpdated": "ISODate('2024-12-31T13:01:19.097Z')"
}
]
例 2 - ウィンドウ演算子の使用
各会社内で最近更新されたストアを取得するには、クエリを実行して会社のフィールドで結果をパーティション分割し、各パーティション内のドキュメントを lastUpdated フィールドの昇順で並べ替え、パーティションごとに並べ替えられた結果を返します。
db.stores.aggregate([{
$setWindowFields: {
partitionBy: "$company",
sortBy: {
lastUpdated: 1
},
output: {
lastUpdatedDateForStore: {
$last: "$lastUpdated",
window: {
documents: ["current", "unbounded"]
}
}
}
}
}])
このクエリによって返された最初の結果は次のとおりです。
[
{
"_id": "First Up Consultants",
"lastUpdated": "ISODate('2024-12-31T13:01:19.097Z')"
}
]