适用对象:
MongoDB vCore
$last
累加器运算符返回指定表达式的一组文档中的最后一个值。 它通常用于 $group
分阶段从已排序的文档集合中获取最终值。
语法
累加器运算符的 $last
语法如下所示:
{
$group: {
_id: <expression>,
<field>: { $last: <expression> }
}
}
参数
DESCRIPTION | |
---|---|
<expression> |
指定要返回最后一个匹配项的字段或值的表达式。 |
示例:
让我们了解 stores
数据集中的示例 json 的用法。
{
"_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74",
"name": "Proseware, Inc. | Home Entertainment Hub - East Linwoodbury",
"location": {
"lat": 70.1272,
"lon": 69.7296
},
"staff": {
"totalStaff": {
"fullTime": 19,
"partTime": 20
}
},
"sales": {
"totalSales": 151864,
"salesByCategory": [
{
"categoryName": "Sound Bars",
"totalSales": 2120
},
{
"categoryName": "Home Theater Projectors",
"totalSales": 45004
},
{
"categoryName": "Game Controllers",
"totalSales": 43522
},
{
"categoryName": "Remote Controls",
"totalSales": 28946
},
{
"categoryName": "VR Games",
"totalSales": 32272
}
]
},
"promotionEvents": [
{
"eventName": "Massive Markdown Mania",
"promotionalDates": {
"startDate": {
"Year": 2023,
"Month": 6,
"Day": 29
},
"endDate": {
"Year": 2023,
"Month": 7,
"Day": 9
}
}
},
{
"eventName": "Major Bargain Bash",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 9,
"Day": 21
},
"endDate": {
"Year": 2024,
"Month": 9,
"Day": 30
}
}
}
]
}
示例 1:按日期获取最后一次促销活动
按日期排序时,通过对商店进行分组并查找最后一个促销事件来获取每个商店的最新促销事件。
db.stores.aggregate([
{ $unwind: "$promotionEvents" },
{ $sort: {
"promotionEvents.promotionalDates.startDate.Year": 1,
"promotionEvents.promotionalDates.startDate.Month": 1,
"promotionEvents.promotionalDates.startDate.Day": 1
}
},
{
$group: {
_id: "$_id",
storeName: { $last: "$name" },
lastPromotionEvent: { $last: "$promotionEvents.eventName" },
lastPromotionStartDate: { $last: "$promotionEvents.promotionalDates.startDate" }
}
}
])
这将生成显示每个商店的最新促销事件的输出:
[
{
_id: '64ec6589-068a-44a6-be5b-9d37bb0a90f1',
storeName: 'First Up Consultants | Computer Gallery - West Cathrine',
lastPromotionEvent: 'Blowout Bargain Bash',
lastPromotionStartDate: { Year: 2024, Month: 9, Day: 21 }
},
{
_id: 'a58d0356-493b-44e6-afab-260aa3296930',
storeName: 'Fabrikam, Inc. | Outdoor Furniture Nook - West Lexie',
lastPromotionEvent: 'Big Bargain Bash',
lastPromotionStartDate: { Year: 2024, Month: 9, Day: 21 }
},
.
.
.
]
示例 2:按销售额获取最后一个销售类别
查找每个商店的最高销售类别(最后一次按销售金额排序)。
db.stores.aggregate([
{ $unwind: "$sales.salesByCategory" },
{ $sort: { "sales.salesByCategory.totalSales": 1 } },
{
$group: {
_id: "$_id",
storeName: { $last: "$name" },
topSellingCategory: { $last: "$sales.salesByCategory.categoryName" },
topSalesAmount: { $last: "$sales.salesByCategory.totalSales" }
}
}
])
这将返回每个商店销售额最高的类别:
[
{
_id: '2e07b49d-1730-491b-b847-44b6a34812c1',
storeName: 'VanArsdel, Ltd. | Electronics Market - North Bransonborough',
topSellingCategory: 'iPads',
topSalesAmount: 37113
},
{
_id: '4a99546f-a1d2-4e61-ae9f-b8c7c1faf73c',
storeName: 'Lakeshore Retail | Stationery Nook - West Van',
topSellingCategory: 'Pencils',
topSalesAmount: 33447
},
.
.
.
]