Skip to main content

group

Definition

The group stage combines multiple documents with the same field, fields, or expression into a single document according to a group key. The result is one document per unique group key.

A group key is often a field, or group of fields. The group key can also be the result of an expression. Use the _id field in the $group pipeline stage to set the group key.

Read the official MongoDB documentation

Syntax

group has the following form:

group _id=field (,varname=accumulator)*

_id field

The _id expression specifies the group key. If you specify an _id value of null, or any other constant value, the group stage returns a single document that aggregates values across all of the input documents.

Accumulators

The accumulator operators must be one of the following:

NameDescription
addToSetReturns an array of unique expression values for each group. Order of the array elements is undefined
avgReturns an average of numerical values. Ignores non-numeric values
bottomReturns the bottom element within a group according to the specified sort order
bottomNReturns an aggregation of the bottom n fields within a group, according to the specified sort order
concatArraysReturns a single array that combines the elements of two or more arrays
countReturns the number of documents in a group
firstReturns the result of an expression for the first document in a group
firstNReturns an aggregation of the first n elements within a group. Only meaningful when documents are in a defined order. Distinct from the $firstN array operator
lastReturns the result of an expression for the last document in a group
lastNReturns an aggregation of the last n elements within a group. Only meaningful when documents are in a defined order. Distinct from the $lastN array operator
maxReturns the highest expression value for each group
maxNReturns an aggregation of the n maximum valued elements in a group. Distinct from the $maxN array operator
medianReturns an approximation of the median, the 50th percentile, as a scalar value
mergeObjectsReturns a document created by combining the input documents for each group
minReturns the lowest expression value for each group
minNReturns an aggregation of the n minimum valued elements in a group. Distinct from the $minN array operator
percentileReturns an array of scalar values that correspond to specified percentile values
pushReturns an array of expression values for documents in each group
setUnionTakes two or more arrays and returns an array containing the elements that appear in any input array
stdDevPopReturns the population standard deviation of the input values
stdDevSampReturns the sample standard deviation of the input values
sumReturns a sum of numerical values. Ignores non-numeric values
topReturns the top element within a group according to the specified sort order
topNReturns an aggregation of the top n fields within a group, according to the specified sort order

Examples