适用对象:
MongoDB vCore
$top
累加器运算符根据指定的排序顺序从组返回顶部元素。 它将排序和选择组合在一个作中,从而有效地查找最高值或最低值,而无需单独的排序阶段。
语法
累加器运算符的 $top
语法如下所示:
{
$group: {
_id: <expression>,
<field>: {
$top: {
sortBy: { <field1>: <sort order>, <field2>: <sort order>, ... },
output: <expression>
}
}
}
}
参数
DESCRIPTION | |
---|---|
sortBy |
使用具有字段名称和排序方向的文档指定排序顺序(1 表示升序,-1 降序)。 |
output |
指定要从顶部文档返回的字段或值的表达式。 |
示例:
让我们了解 stores
数据集中的示例 json 的用法。
{
"_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74",
"name": "Proseware, Inc. | Home Entertainment Hub - East Linwoodbury",
"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
}
},
"discounts": [
{
"categoryName": "DVD Players",
"discountPercentage": 14
},
{
"categoryName": "Televisions",
"discountPercentage": 22
}
]
}
]
}
示例 1:获取每个商店最畅销的类别
查找每个商店的最高销售类别。
db.stores.aggregate([
{ $unwind: "$sales.salesByCategory" },
{
$group: {
_id: "$_id",
storeName: { $first: "$name" },
topSellingCategory: {
$top: {
sortBy: { "sales.salesByCategory.totalSales": -1 },
output: {
categoryName: "$sales.salesByCategory.categoryName",
totalSales: "$sales.salesByCategory.totalSales"
}
}
}
}
}
])
这将生成显示每个商店最畅销类别的输出:
[
{
_id: 'b1d86d1f-8705-4157-b64c-a9eda0df4921',
storeName: 'VanArsdel, Ltd. | Baby Products Haven - West Kingfort',
topSellingCategory: { categoryName: 'Baby Monitors', totalSales: 49585 }
},
{
_id: '22e6367e-8341-415f-9795-118d2b522abf',
storeName: 'Adatum Corporation | Outdoor Furniture Mart - Port Simone',
topSellingCategory: { categoryName: 'Outdoor Benches', totalSales: 4976 }
},
.
.
.
]
示例 2:按类别获取最高折扣
查找每个商店的所有促销事件中折扣百分比最高的类别。
db.stores.aggregate([
{ $unwind: "$promotionEvents" },
{ $unwind: "$promotionEvents.discounts" },
{
$group: {
_id: "$_id",
storeName: { $first: "$name" },
highestDiscount: {
$top: {
sortBy: { "promotionEvents.discounts.discountPercentage": -1 },
output: {
categoryName: "$promotionEvents.discounts.categoryName",
discountPercentage: "$promotionEvents.discounts.discountPercentage",
eventName: "$promotionEvents.eventName"
}
}
}
}
}
])
这将显示每个商店的最高折扣百分比的类别:
[
{
_id: '64ec6589-068a-44a6-be5b-9d37bb0a90f1',
storeName: 'First Up Consultants | Computer Gallery - West Cathrine',
highestDiscount: {
categoryName: 'Gaming Accessories',
discountPercentage: 24,
eventName: 'Crazy Markdown Madness'
}
},
{
_id: 'a58d0356-493b-44e6-afab-260aa3296930',
storeName: 'Fabrikam, Inc. | Outdoor Furniture Nook - West Lexie',
highestDiscount: {
categoryName: 'Fire Pits',
discountPercentage: 22,
eventName: 'Savings Showdown'
}
},
.
.
.
]