$sort (aggregation)

Definition

  • $sort
  • Sorts all input documents and returns them to the pipeline in sortedorder.

The $sort stage has the following prototype form:

  1. { $sort: { <field1>: <sort order>, <field2>: <sort order> ... } }

$sort takes a document that specifies the field(s) tosort by and the respective sort order. <sort order> can have oneof the following values:

ValueDescription1Sort ascending.-1Sort descending.{ $meta: "textScore" }Sort by the computed textScore metadata in descendingorder. See Metadata Sort for an example.

If sorting on multiple fields, sort order is evaluated from left toright. For example, in the form above, documents are first sorted by<field1>. Then documents with the same <field1> values arefurther sorted by <field2>.

Examples

Ascending/Descending Sort

For the field or fields to sort by, set the sort order to 1 or -1 tospecify an ascending or descending sort respectively, as in the following example:

  1. db.users.aggregate(
  2. [
  3. { $sort : { age : -1, posts: 1 } }
  4. ]
  5. )

This operation sorts the documents in the users collection,in descending order according by the age field and then inascending 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, decimals)
  • Symbol, String
  • Object
  • Array
  • BinData
  • ObjectId
  • Boolean
  • Date
  • Timestamp
  • Regular Expression
  • MaxKey (internal type)For details on the comparison/sort order for specific types, seeComparison/Sort Order.

Metadata Sort

Specify in the { <sort-key> } document, a new field name for thecomputed metadata and specify the $meta expression as itsvalue, as in the following example:

  1. db.users.aggregate(
  2. [
  3. { $match: { $text: { $search: "operating" } } },
  4. { $sort: { score: { $meta: "textScore" }, posts: -1 } }
  5. ]
  6. )

This operation uses the $text operator to match the documents,and then sorts first by the "textScore" metadata and then bydescending order of the posts field. The specified metadatadetermines the sort order. For example, the "textScore" metadatasorts in descending order. See $meta for more informationon metadata.

$sort Operator and Memory

$sort + $limit Memory Optimization

When a $sort precedes a $limit and there are nointervening stages that modify the number of documents, the optimizer cancoalesce the $limit into the $sort. This allowsthe $sort operation to onlymaintain the top n results as it progresses, where n is thespecified limit, and ensures that MongoDB only needs to store n items in memory.This optimization still applies when allowDiskUse is true andthe n items exceed the aggregation memory limit.

Optimizations are subject to change between releases.

$sort and Memory Restrictions

The $sort stage has a limit of 100 megabytes of RAM. Bydefault, if the stage exceeds this limit, $sort willproduce an error. To allow for the handling of large datasets, set theallowDiskUse option to true to enable $sortoperations to write to temporary files. See the allowDiskUseoption in db.collection.aggregate() method and theaggregate command for details.

$sort Operator and Performance

$sort operator can take advantage of an index whenplaced at the beginning of the pipeline or placed beforethe $project,$unwind, and $group aggregation operators.If $project, $unwind, or $groupoccur prior to the $sort operation, $sortcannot use any indexes.

See also

Aggregation with the Zip Code Data Set,Aggregation with User Preference Data