$sort
The $sort aggregation stage orders documents in the pipeline based on specified field values. Documents are arranged in ascending or descending order according to the sort criteria provided.
Parameters
-
field: The field name to sort by. -
order: Use1for ascending order or-1for descending order.
Example (MongoDB Shell)
The following example demonstrates using the $sort stage to order products by price in descending order.
Create sample documents
db.products.insertMany([ { _id: 1, name: "Laptop", category: "Electronics", price: 1200 }, { _id: 2, name: "Mouse", category: "Electronics", price: 25 }, { _id: 3, name: "Desk", category: "Furniture", price: 350 }, { _id: 4, name: "Chair", category: "Furniture", price: 150 }, { _id: 5, name: "Monitor", category: "Electronics", price: 400 } ]);
Query example
db.products.aggregate([ { $sort: { price: -1 } } ]);
Output
[
{ _id: 1, name: 'Laptop', category: 'Electronics', price: 1200 },
{ _id: 5, name: 'Monitor', category: 'Electronics', price: 400 },
{ _id: 3, name: 'Desk', category: 'Furniture', price: 350 },
{ _id: 4, name: 'Chair', category: 'Furniture', price: 150 },
{ _id: 2, name: 'Mouse', category: 'Electronics', price: 25 }
]
Code examples
To view a code example for using the $sort aggregation stage, choose the tab for the language that you want to use: