- Reference >
- Operators >
- Aggregation Framework Operators >
- Pipeline 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)
MongoDB treats some types as equivalent for comparison purposes. For instance, numeric types undergo conversion before comparison.
The comparison treats a non-existent field as it would an empty BSON Object. As such, a sort on the
a
field in documents{ }
and{ a: null }
would treat the documents as equivalent in sort order.With arrays, a less-than comparison or an ascending sort compares the smallest element of arrays, and a greater-than comparison or a descending sort compares the largest element of the arrays. As such, when comparing a field whose value is a single-element array (e.g.
[ 1 ]
) with non-array fields (e.g.2
), the comparison is between1
and2
. A comparison of an empty array (e.g.[ ]
) treats the empty array as less thannull
or a missing field.Important
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:$project
,$unwind
, and$group
.Changed in version 2.4:
$sort
and memory requirements:- When a
$sort
immediately precedes a$limit
in the pipeline, the$sort
operation only maintains the top n results as it progresses, where n is the specified limit, and MongoDB only needs to store the number of items specified by$limit
in memory. Before MongoDB 2.4,$sort
would sort all the results in memory, and then limit the results to n results. - Unless the
$sort
operator can use an index or immediately precedes a$limit
, the$sort
operation must fit within memory. Before MongoDB 2.4, unless the$sort
operator can use an index, the$sort
operation must fit within memory.
$sort
produces an error if the operation consumes 10 percent or more of RAM.