- Reference >
- Operators >
- Aggregation Pipeline Operators >
- Pipeline Aggregation Stages >
- $sort (aggregation)
$sort (aggregation)¶
- $sort¶
Sorts all input documents and returns them to the pipeline in sorted order.
The $sort stage has the following prototype form:
{ $sort: { <field1>: <sort order>, <field2>: <sort order> ... } }
$sort takes a document that specifies the field(s) to sort by and the respective sort order. <sort order> can have one of the following values:
- 1 to specify ascending order.
- -1 to specify descending order.
- { $meta: "textScore" } to sort by the computed textScore metadata in descending order. See Metadata Sort for an example.
Examples¶
Ascending/Descending Sort¶
To ascending order for a field or fields to sort by and a value of 1 or -1 to specify an ascending or descending sort respectively, as in the following example:
db.users.aggregate(
[
{ $sort : { age : -1, posts: 1 } }
]
)
This operation sorts the documents in the users collection, in descending order according by the age field and then in ascending order according to the value in the posts 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 between 1 and 2. A comparison of an empty array (e.g. [ ]) treats the empty array as less than null or a missing field.
MongoDB sorts BinData in the following order:
- First, the length or size of the data.
- Then, by the BSON one-byte subtype.
- Finally, by the data, performing a byte-by-byte comparison.
Metadata Sort¶
Specify in the { <sort-key> } document, a new field name for the computed metadata and specify the $meta expression as its value, as in the following example:
db.users.aggregate(
[
{ $match: { $text: { $search: "operating" } } },
{ $sort: { score: { $meta: "textScore" }, posts: -1 } }
]
)
This operation uses the $text operator to match the documents, and then sorts first by the "textScore" metadata and then by descending order of the posts field. The specified metadata determines the sort order. For example, the "textScore" metadata sorts in descending order. See $meta for more information on metadata.
$sort Operator and Memory¶
$sort + $limit Memory Optimization¶
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 n items in memory. This optimization still applies when allowDiskUse is true and the n items exceed the aggregation memory limit.
在 2.4 版更改: Before MongoDB 2.4, $sort would sort all the results in memory, and then limit the results to n results.
Optimizations are subject to change between releases.
$sort and Memory Restrictions¶
The $sort stage has a limit of 100 megabytes of RAM. By default, if the stage exceeds this limit, $sort will produce an error. To allow for the handling of large datasets, set the allowDiskUse option to true to enable $sort operations to write to temporary files. See the allowDiskUse option in db.collection.aggregate() method and the aggregate command for details.
在 2.6 版更改: The memory limit for $sort changed from 10 percent of RAM to 100 megabytes of RAM.