Yes, you can sort by multiple fields in MongoDB using the sort stage in an aggregation pipeline or in a query. You specify the fields you want to sort by in an array, and you can define the sort order for each field (ascending or descending).
Syntax
The syntax for sorting by multiple fields is as follows:
db.collection.find().sort({ field1: 1, field2: -1 })
1indicates ascending order.-1indicates descending order.
Example
Here’s an example of sorting documents in a collection called products by category in ascending order and by price in descending order:
db.products.find().sort({ category: 1, price: -1 })
Explanation
- category: The documents will be sorted first by the
categoryfield in ascending order. - price: Within each category, the documents will be sorted by the
pricefield in descending order.
Aggregation Example
You can also sort by multiple fields in an aggregation pipeline:
db.orders.aggregate([
{
$sort: {
customerId: 1, // Sort by customerId in ascending order
orderDate: -1 // Then sort by orderDate in descending order
}
}
])
Summary
Sorting by multiple fields allows you to control the order of your results more precisely, enabling you to organize data according to your specific requirements.
