$top
The `$top` operator sorts documents on one or more fields specified by the query and returns the first document matching the filtering criteria. It combines sorting and selection in a single operation.
Syntax
{
$top: {
output: [listOfFields],
sortBy: {
<fieldName>: <sortOrder>
}
}
}
Parameters
listOfFields
objectrequiredThe list of fields to be returned for the first document in the result set.
fieldName
stringrequiredThe field to use for sorting the result set.
sortOrder
numberrequired1 or -1. 1 implies ascending order while -1 implies descending order.
Examples
Sample Data
{
"_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
"name": "First Up Consultants | Beverage Shop",
"sales": {
"totalSales": 75670
},
"promotionEvents": [
{
"eventName": "Unbeatable Bargain Bash",
"discounts": [
{ "categoryName": "Whiskey", "discountPercentage": 7 }
]
}
]
}
Get the top selling category per store
Find the highest-selling category within a company using $top.
This query sorts documents by total sales and returns the top document per company.
Query:
db.stores.aggregate([
{
$match: { company: { $in: ["First Up Consultants"] } }
},
{
$group: {
_id: "$company",
topSales: {
$top: {
output: ["$company", "$sales"],
sortBy: { "sales.totalSales": -1 }
}
}
}
}
])
Output:
[
{
"_id": "First Up Consultants",
"topSales": [
"First Up Consultants",
{
"salesByCategory": [
{ "categoryName": "Towel Sets", "totalSales": 520 },
{ "categoryName": "Bath Accessories", "totalSales": 41710 }
],
"revenue": 279183
}
]
}
]
Get the highest discount by promotion category
Fetch the highest discount per sales category across all promotions.
This query unwinds promotion events and finds the maximum discount per category.
Query:
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"
}
}
}
}
}
])
Output:
[
{
"_id": "64ec6589-068a-44a6-be5b-9d37bb0a90f1",
"storeName": "First Up Consultants | Computer Gallery",
"highestDiscount": {
"categoryName": "Gaming Accessories",
"discountPercentage": 24
}
}
]