$group (aggregation) — MongoDB Manual
The $group
stage separates documents into groups according to a
“group key”. The output is one document for each unique group key.
A group key is often a field, or group of fields. The group key can
also be the result of an expression. Use the _id
field in the
$group
pipeline stage to set the group key. See below for
usage examples .
In the $group
stage output, the _id
field is set to the
group key for that document.
The output documents can also contain additional fields that are
set using accumulator expressions .
Note
$group
does not order its output documents.
The $group
stage has the following prototype form:
{ $group
: {
_id
: < expression > , < field1 > : { < accumulator1 > : < expression1 > } , ... } }
Field
Description
_id
_id
expression specifies the group key.
If you specify an _id
value of null, or any other
constant value, the $group
stage returns a single
document that aggregates values across all of the input
documents.
Required. Theexpression specifies the group key. If you specify anvalue of null, or any other constant value, thestage returns a single document that aggregates values across all of the input documents. See the Group by Null example .
field
Optional. Computed using the accumulator operators .
The _id
and the accumulator operators
can accept any valid expression
. For more information on
expressions, see Expressions .