- Reference >
- Operators >
- Aggregation Framework Operators >
- Pipeline Aggregation Operators >
- $group (aggregation)
$group (aggregation)¶
On this page
-
$group
¶ Groups documents together for the purpose of calculating aggregate values based on a collection of documents. In practice,
$group
often supports tasks such as average page views for each page in a website on a daily basis.Important
The output of
$group
is not ordered.The output of
$group
depends on how you define groups. Begin by specifying an identifier (i.e. an_id
field) for the group you’re creating with this pipeline. For this_id
field, you can specify various expressions, including a single field from the documents in the pipeline, a computed value from a previous stage, a document that consists of multiple fields, and other valid expressions, such as constant or subdocument fields. You can use$project
operators in expressions for the_id
field.The following example of an
_id
field specifies a document that consists of multiple fields:Every
$group
expression must specify an_id
field. In addition to the_id
field,$group
expression can include computed fields. These other fields must use one of the following accumulators:With the exception of the
_id
field,$group
cannot output nested documents.
Warning
The aggregation system currently stores $group
operations in
memory, which may cause problems when processing a larger number
of groups.
Example¶
Consider the following example:
This aggregation pipeline groups by the author
field and computes
two fields, the first docsPerAuthor
is a counter field that
increments by one for each document with a given author field using
the $sum
function. The viewsPerAuthor
field is the sum of
all of the pageViews
fields in the documents for each group.