To achieve the desired sorting where items of the “Other” category always appear after everything else, you can modify your aggregation query by using a combination of $cond and $eq operators to assign a sort value based on the category. Here’s the modified query:
$addFields: This stage adds a new field called sortValue. The value of sortValue is determined using the $cond operator, which checks if the category is “Other”. If it is, it assigns a sort value of 2; otherwise, it assigns a sort value of 1.
$sort: This stage sorts the documents first by sortValue in ascending order (so that “Other” is always at the end), and then by category in ascending order.
$project: This stage removes the sortValue field from the output since it was only used for sorting purposes.
With this modified query, the result will have items sorted by category, with items of the “Other” category always appearing after everything else.
Note: This query is an example based on the data provided by you. Kindly, test and modify the query based on your use case and requirements.
Since the sort is based on a computed value, then no index will be used so a memory sort will be done. If the result set is small it is not an issue. If the result set is large you may try the following alternatives:
1 - Simply do 2 queries, one with a $match that uses $ne:“Other” and then a second one with $eq:“Other”. For some data set doing 2 database access might be faster than a memory sort.
2 - Permanently update the collection with the sortValue, then have an index with sortValue:1,category:1.