- 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
$group
depends on how you define groups. Begin by specifying an identifier (i.e. a_id
field) 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
_id
field,$group
cannot output nested documents.Important
The output of
$group
is not ordered.Every group expression must specify an
_id
field. You may specify the_id
field 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
author
field and computes two fields, the firstdocsPerAuthor
is a counter field that adds one for each document with a given author field using the$sum
function. TheviewsPerAuthor
field is the sum of all of thepageViews
fields in the documents for each group.Each field defined for the
$group
must use one of the group aggregation function listed below to generate its composite value:Warning
The aggregation system currently stores
$group
operations in memory, which may cause problems when processing a larger number of groups.