Navigation
This version of the documentation is archived and no longer supported.

$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:

{ _id : { author: '$author', pageViews: '$pageViews', posted: '$posted' } }

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.

Tip

Use $project as needed to rename the grouped field after a $group operation.

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:

db.article.aggregate(
    { $group : {
        _id : "$author",
        docsPerAuthor : { $sum : 1 },
        viewsPerAuthor : { $sum : "$pageViews" }
    }}
);

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.