How to sort in mongoose?
Sort data in Mongoose using .sort({ field: 1})
for ascending, and .sort({ field: -1 })
for descending order.
Remember to chain .sort()
after .find()
. Need to sort on multiple fields? Just extend the object: .sort({ field1: 1, field2: -1 })
.
Sort the Sortables
Hierarchical multi-field sort
Sorting on multiple fields is straightforward: simply set the priority by sequencing the fields in the sort object.
Case-insensitive string sorting
Sorting strings can be tricky. You will need to set a collation with your locale
to sort case-insensitively:
Paginated sorting
You can combine .sort()
with .limit()
and .skip()
to implement pagination:
Pro-level Sorting Strategies and Pitfalls
Mandatory .exec() usage
Always remember to call .exec() to execute the query and return a promise. It makes your code cleaner and ready for using then
.
Nested-field sorting
Dot notation unlocks sorting by nested fields:
Error handling and precautions
ALWAYS handle errors to catch issues related to invalid fields or sorting logic:
Performance-focused sorting
In large datasets, sorting on indexed fields yields better performance. Mongoose wisely uses same index for filtering and sorting the data.
Aggregation pipeline sorting
In aggregation pipelines, the $sort
command sorts in style:
Was this article helpful?