The sort stage take all documents it receives and passes them into the next stage in the specified sort order.
{"$sort": {<property1>: <sort order>, <property2>: <sort order>, ...}}
Where sort order can be 1
for ascending or -1
for descending.
Performance Considerations
To optimize performance, it is best to use $sort
at the beginning of the pipeline or near the beginning, after a $match
and $limit
. And $sort
should always proceed $project
, $unwind
, or $group
if it is required -- otherwise your query may be slow or time out.
Examples
GET /c_patients?pipeline=[{"$match": {"c_gender": "f"}},{"$limit": 2},{"$sort": {"c_name.c_last": 1},{"$project": {"c_name": 1}}}]
{
"data": [
{
"_id": "59496035bfd25d0100661faf",
"c_name": {
"c_first": "Holly",
"c_last": "Forrester"
}
},
{
"_id": "59495fc1514ef1010000598d",
"c_name": {
"c_first": "Jane",
"c_last": "Smith"
}
}
],
"hasMore": false,
"object": "list"
}