- Reference >
- Operators >
- Aggregation Pipeline Stages >
- $group (aggregation)
$group (aggregation)¶
On this page
Definition¶
-
$group
¶ Groups input documents by the specified
_id
expression and for each distinct grouping, outputs a document. The_id
field of each output document contains the unique group by value. The output documents can also contain computed fields that hold the values of some accumulator expression.Note
$group
does not order its output documents.The
$group
stage has the following prototype form:Field Description _id
Required. If you specify an _id
value of null, or any other constant value, the$group
stage calculates accumulated values for all the input documents as a whole. See example of Group by Null.field
Optional. Computed using the accumulator operators. The
_id
and the accumulator operators can accept any validexpression
. For more information on expressions, see Expressions.
Considerations¶
Accumulator Operator¶
The <accumulator>
operator must be one of the following accumulator
operators:
Name | Description |
---|---|
$accumulator |
Returns the result of a user-defined accumulator function. |
$addToSet |
Returns an array of unique expression values for each group. Order of the array elements is undefined. |
$avg |
Returns an average of numerical values. Ignores non-numeric values. |
$first |
Returns a value from the first document for each group. Order is only defined if the documents are in a defined order. Distinct from the |
$last |
Returns a value from the last document for each group. Order is only defined if the documents are in a defined order. Distinct from the |
$max |
Returns the highest expression value for each group. |
$mergeObjects |
Returns a document created by combining the input documents for each group. |
$min |
Returns the lowest expression value for each group. |
$push |
Returns an array of expression values for each group. |
$stdDevPop |
Returns the population standard deviation of the input values. |
$stdDevSamp |
Returns the sample standard deviation of the input values. |
$sum |
Returns a sum of numerical values. Ignores non-numeric values. |
$group
Operator and Memory¶
The $group
stage has a limit of 100 megabytes of RAM. By
default, if the stage exceeds this limit, $group
returns an
error. To allow for the handling of large datasets, set the
allowDiskUse
option to
true
. This flag enables $group
operations to write to
temporary files. For more information, see the
db.collection.aggregate()
method and the
aggregate
command.
Optimization to Return the First Document of Each Group¶
If a pipeline sorts
and groups
by the same field and the $group
stage only uses the
$first
accumulator operator, consider adding an index on the grouped field which matches the sort order. In some
cases, the $group
stage can use the index to quickly find
the first document of each group.
Example
If a collection named foo
contains an index { x: 1, y: 1 }
,
the following pipeline can use that index to find the first document
of each group:
Examples¶
Count the Number of Documents in a Collection¶
From the mongo
shell, create a sample collection named
sales
with the following documents:
The following aggregation operation uses the $group
stage
to count the number of documents in the sales
collection:
The operation returns the following result:
This aggregation operation is equivalent to the following SQL statement:
See also
Retrieve Distinct Values¶
The following aggregation operation uses the $group
stage
to retrieve the distinct item values from the sales
collection:
The operation returns the following result:
Group by Item Having¶
The following aggregation operation groups documents by the item
field, calculating the total sale amount per item and returning only
the items with total sale amount greater than or equal to 100:
- First Stage:
- The
$group
stage groups the documents byitem
to retrieve the distinct item values. This stage returns thetotalSaleAmount
for each item. - Second Stage:
- The
$match
stage filters the resulting documents to only return items with atotalSaleAmount
greater than or equal to 100.
The operation returns the following result:
This aggregation operation is equivalent to the following SQL statement:
See also
Calculate Count, Sum, and Average¶
From the mongo
shell, create a sample collection named
sales
with the following documents:
Group by Day of the Year¶
The following pipeline calculates the total sales amount, average sales quantity, and sale count for each day in the year 2014:
- First Stage:
- The
$match
stage filters the documents to only pass documents from the year 2014 to the next stage. - Second Stage:
- The
$group
stage groups the documents by date and calculates the total sale amount, average quantity, and total count of the documents in each group. - Third Stage:
- The
$sort
stage sorts the results by the total sale amount for each group in descending order.
The operation returns the following results:
This aggregation operation is equivalent to the following SQL statement:
See also
$match
$sort
db.collection.countDocuments()
which wraps the$group
aggregation stage with a$sum
expression.
Group by null
¶
The following aggregation operation specifies a group _id
of
null
, calculating the total sale amount, average quantity, and count of
all documents in the collection.
The operation returns the following result:
This aggregation operation is equivalent to the following SQL statement:
See also
$count
db.collection.countDocuments()
which wraps the$group
aggregation stage with a$sum
expression.
Pivot Data¶
From the mongo
shell, create a sample collection named
books
with the following documents:
Group title
by author
¶
The following aggregation operation pivots the data in the books
collection to have titles grouped by authors.
The operation returns the following documents:
Group Documents by author
¶
The following aggregation operation groups documents by author
:
- First Stage:
$group
uses the$$ROOT
system variable to group the entire documents by authors. This stage passes the following documents to the next stage:- Second Stage:
$addFields
adds a field to the output containing the total copies of books for each author.Note
The resulting documents must not exceed the
BSON Document Size
limit of 16 megabytes.The operation returns the following documents:
See also
Additional Resources¶
The Aggregation with the Zip Code Data Set
tutorial provides an extensive example of the $group
operator in a common use case.