Aggregation task - $sort

A scope aggregation task that orders the documents in ascending or descending order.

Documents can be sorted on specified fields in ascending or descending order. If the sort task follows other tasks, the field names must be the alias names of previously selected attributes.

Syntax diagram

Read syntax diagramSkip visual syntax diagram{$sort:{field: sortorder [, ...]}}

Command arguments

field
The JSON field name or alias name
sortorder: 1 = ascending, -1 = descending

Example

In the furniture collection, to sort documents by material in descending order and to sort documents by type in ascending order, run the following command:

db.furniture.aggregate({"$sort":{"material":-1,"type":1})