Skip to main content

$sort

The $sort stage in MongoDB's aggregation pipeline is used to sort the documents based on one or more fields. Sorting can be done in ascending or descending order, and it's often used in conjunction with other aggregation stages like $group, $match, and $project to organize the output.

Basic Syntax

The basic syntax of the $sort stage is as follows:

db.collection.aggregate([
{
$sort: {
field1: <sort order>,
field2: <sort order>,
// ...
}
}
]);
  • field1, field2, ...: The fields by which the documents will be sorted.
  • <sort order>: An integer specifying the sort order. Use 1 for ascending and -1 for descending.

Examples

Simple Sorting

To sort documents by the amount field in ascending order:

db.orders.aggregate([
{
$sort: { amount: 1 }
}
]);

Multiple Field Sorting

To sort documents first by the status field in ascending order and then by the amount field in descending order:

db.orders.aggregate([
{
$sort: { status: 1, amount: -1 }
}
]);

Sorting After Grouping

You can use $sort after $group to sort the grouped results. For example, to group orders by status and then sort by the total amount in descending order:

db.orders.aggregate([
{
$group: {
_id: "$status",
totalAmount: { $sum: "$amount" }
}
},
{
$sort: { totalAmount: -1 }
}
]);

Considerations

  1. Performance: Sorting can be resource-intensive, especially with large datasets. Proper indexing can improve performance.

  2. Memory Limitations: The $sort stage has a memory limit. For larger datasets, you may need to enable the allowDiskUse option.

  3. Order of Stages: Placing $sort after a $match stage and before a $project stage can take advantage of indexes and improve performance.

  4. Data Types: MongoDB uses the BSON data type for comparisons, which may have different sorting behavior compared to other systems for certain data types.