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 a
countfield containing the number of documents belonging to that grouping or category.
The documents are sorted by
countin descending order.
$sortByCountstage has the following prototype form:
Expression 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 field
"$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
businessfields are document fields, then the following
$mergeObjectsexpression, which evaluates to a document, is a valid argument to
However, the following example with the document literal expression is invalid: