- Reference >
- Query, Update, Projection, and Aggregation Operators >
- $sort (aggregation)
$sort (aggregation)¶
-
$sort
¶ The
$sort
pipeline operator sorts all input documents and returns them to the pipeline in sorted order. Consider the following prototype form:This sorts the documents in the collection named
<collection-name>
, according to the key and specification in the{ <sort-key> }
document.Specify the sort in a document with a field or fields that you want to sort by and a value of
1
or-1
to specify an ascending or descending sort respectively, as in the following example:This operation sorts the documents in the
users
collection, in descending order according by theage
field and then in ascending order according to the value in theposts
field.When comparing values of different BSON types, MongoDB uses the following comparison order, from lowest to highest:
- MinKey (internal type)
- Null
- Numbers (ints, longs, doubles)
- Symbol, String
- Object
- Array
- BinData
- ObjectID
- Boolean
- Date, Timestamp
- Regular Expression
- MaxKey (internal type)
Note
MongoDB treats some types as equivalent for comparison purposes. For instance, numeric types undergo conversion before comparison.
Note
The
$sort
cannot begin sorting documents until previous operators in the pipeline have returned all output.$sort
operator can take advantage of an index when placed at the beginning of the pipeline or placed before the following aggregation operators:Warning
Unless the
$sort
operator can use an index, in the current release, the sort must fit within memory. This may cause problems when sorting large numbers of documents.