$sort
The `$sort` stage in the aggregation pipeline is used to order the documents in the pipeline by a specified field or fields. This stage helps you sort data, like arranging sales by amount or events by date.
Syntax
{
$sort: {
<field1>: <sort order>,
<field2>: <sort order>
}
}
Parameters
field
stringrequiredThe field to sort by.
sort order
numberrequiredThe order in which to sort the field. 1 for ascending order and -1 for descending order.
Examples
Sample Data
{
"_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
"name": "First Up Consultants | Beverage Shop",
"sales": {
"totalSales": 75670,
"salesByCategory": [
{ "categoryName": "Wine Accessories", "totalSales": 34440 },
{ "categoryName": "Bitters", "totalSales": 39496 }
]
}
}
Sorting by total sales in descending order
Sort sales categories by their total sales in descending order.
This query unwinds the salesByCategory array and sorts by totalSales.
Query:
db.collection.aggregate([
{
$unwind: "$store.sales.salesByCategory"
},
{
$sort: { "store.sales.salesByCategory.totalSales": -1 }
}
])
Output:
[
{
"_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
"store": {
"name": "Downtown Store",
"sales": {
"salesByCategory": [
{ "category": "Electronics", "totalSales": 15000 },
{ "category": "Clothing", "totalSales": 12000 }
]
}
}
}
]
Sorting by event start date in ascending order
Sort promotion events by their start dates in ascending order.
This query unwinds events and sorts by the startDate field.
Query:
db.collection.aggregate([
{ $unwind: "$store.promotionEvents" },
{ $sort: { "store.promotionEvents.promotionalDates.startDate": 1 } }
])
Output:
[
{
"_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
"store": {
"name": "Downtown Store",
"promotionEvents": [
{ "eventName": "Summer Sale", "promotionalDates": { "startDate": "2024-06-01T00:00:00Z" } }
]
}
}
]