- Reference >
- Operators >
- Aggregation Pipeline Stages >
- $sortByCount (aggregation)
$sortByCount (aggregation)¶
On this page
Definition¶
-
$sortByCount¶ 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$sortByCount:However, the following example with the document literal expression is invalid:
See also
Considerations¶
$sortByCount and Memory Restrictions¶
$sortByCount is subject to the 100 megabyte memory usage limit, but
is able to write temporary files to disk if additional space is
required.
Starting in MongoDB 6.0, pipeline stages that require more than 100
megabytes of memory to execute write temporary files to disk by
default. In earlier verisons of MongoDB, you must pass
{ allowDiskUse: true } to individual find and aggregate
commands to enable this behavior.
Individual find and aggregate commands may override the
allowDiskUseByDefault parameter by either:
- Using
{ allowDiskUse: true }to allow writing temporary files out to disk whenallowDiskUseByDefaultis set tofalse - Using
{ allowDiskUse: false }to probibit writing temporary files out to disk whenallowDiskUseByDefaultis set totrue
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: