- Reference >
- Query, Update, Projection, and Aggregation Operators >
- $group (aggregation)
$group (aggregation)¶
-
$group¶ Groups documents together for the purpose of calculating aggregate values based on a collection of documents. Practically, group often supports tasks such as average page views for each page in a website on a daily basis.
The output of
$groupdepends on how you define groups. Begin by specifying an identifier (i.e. a_idfield) for the group you’re creating with this pipeline. You can specify a single field from the documents in the pipeline, a previously computed value, or an aggregate key made up from several incoming fields. Aggregate keys may resemble the following document:With the exception of the
_idfield,$groupcannot output nested documents.Important
The output of
$groupis not ordered.Every group expression must specify an
_idfield. You may specify the_idfield as a dotted field path reference, a document with multiple fields enclosed in braces (i.e.{and}), or a constant value.Consider the following example:
This groups by the
authorfield and computes two fields, the firstdocsPerAuthoris a counter field that adds one for each document with a given author field using the$sumfunction. TheviewsPerAuthorfield is the sum of all of thepageViewsfields in the documents for each group.Each field defined for the
$groupmust use one of the group aggregation function listed below to generate its composite value:Warning
The aggregation system currently stores
$groupoperations in memory, which may cause problems when processing a larger number of groups.