Accumulators

Group Accumulators

These functions are available for use in the $group stage, accumulators are operators that maintain their state (e.g. totals, maximums, minimums, and related data) as information progress through the pipeline.

When used as accumulators in the $group stage, these operators take as input a single expression, evaluating the expression once for each input document, and maintain their stage for the group of documents that share the same group key.

For example:

Variable

Access via $

Brief Description

accumulator

$accumulator

Returns the result of a user-defined accumulator function

addToSet

$addToSet

Returns an array of unique expression values for each group. Order of the array elements is undefined

avg

$avg

Returns an average of numerical values. Ignores non-numeric values

Accumulators

Some operators that are available as accumulators for the $group stage are also available for use in other. When used in these other stages, these operators do not maintain their state and can take as input either a single argument or multiple arguments.

For example:

Variable

Access via $

Brief Description

addToSet

$addtoSet

Returns array of unique pushed values

avg

$avg

Calculates the average of a number property or expression in the group.

count

$count

Performs a count of a grouped documents or, if the property is an array, a count of the number of elements.

first

$first

Returns the first value from the group. The result depends on the sort field(s)

last

$last

Returns the last value from the group. The result depends on the sort field(s)

mergeObjects

$mergeObjects

Combines multiple documents into a single document

min

$min

Returns the smallest value from the group.

max

$max

Returns the largest value from the group

push

$push

Returns the array of pushed values

sum

$sum

Calculates the sum of a number property or expression in the group

Last updated