- 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,
$groupoften supports tasks such as average page views for each page in a website on a daily basis.Important
The output of
$groupis not ordered.The output of
$groupdepends on how you define groups. Begin by specifying an identifier (i.e. an_idfield) for the group you’re creating with this pipeline. For this_idfield, 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$projectoperators in expressions for the_idfield.The following example of an
_idfield specifies a document that consists of multiple fields:Every
$groupexpression must specify an_idfield. In addition to the_idfield,$groupexpression can include computed fields. These other fields must use one of the following accumulators:With the exception of the
_idfield,$groupcannot 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.