- Reference >
- Operators >
- Aggregation Pipeline Stages >
- $sortByCount (aggregation)
$sortByCount (aggregation)¶
On this page
Definition¶
-
$sortByCount¶ New in version 3.4.
Groups incoming documents based on the value of a specified expression, then computes the count of documents in each distinct group.
Each output document contains two fields: an
_idfield containing the distinct grouping value, and acountfield containing the number of documents belonging to that grouping or category.The documents are sorted by
countin descending order.The
$sortByCountstage has the following prototype form:Field Description expressionExpression to group by. You can specify any expression except for a document literal.
To specify a field path, prefix the field name with a dollar sign
$and enclose it in quotes. For example, to group by the fieldemployee, specify"$employee"as the expression.Although you cannot specify a document literal for the group by expression, you can, however, specify a field or an expression that evaluates to a document. For example, if
employeeandbusinessfields are document fields, then the following$mergeObjectsexpression, which evaluates to a document, is a valid argument to$sortByCounts:However, the following example with the document literal expression is invalid:
See also
Behavior¶
The $sortByCount stage is equivalent to the
following $group + $sort sequence:
Example¶
Consider a collection exhibits with the following documents:
The following operation unwinds the tags
array and uses the $sortByCount stage to count the
number of documents associated with each tag:
The operation returns the following documents, sorted in descending order by count: