- Reference >
- Operators >
- Aggregation Pipeline Stages >
- $group (aggregation)
$group (aggregation)¶
On this page
Definition¶
-
$group¶ Groups input documents by the specified
_idexpression and for each distinct grouping, outputs a document. The_idfield 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
$groupdoes not order its output documents.The
$groupstage has the following prototype form:Field Description _idRequired. If you specify an _idvalue of null, or any other constant value, the$groupstage calculates accumulated values for all the input documents as a whole. See example of Group by Null.fieldOptional. Computed using the accumulator operators. The
_idand 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
$groupstage groups the documents byitemto retrieve the distinct item values. This stage returns thetotalSaleAmountfor each item. - Second Stage:
- The
$matchstage filters the resulting documents to only return items with atotalSaleAmountgreater 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
$matchstage filters the documents to only pass documents from the year 2014 to the next stage. - Second Stage:
- The
$groupstage 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
$sortstage 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$sortdb.collection.countDocuments()which wraps the$groupaggregation stage with a$sumexpression.
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
$countdb.collection.countDocuments()which wraps the$groupaggregation stage with a$sumexpression.
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:
$groupuses the$$ROOTsystem variable to group the entire documents by authors. This stage passes the following documents to the next stage:- Second Stage:
$addFieldsadds a field to the output containing the total copies of books for each author.Note
The resulting documents must not exceed the
BSON Document Sizelimit 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.