\$reduce (aggregation)

Definition

`\$reduce`

New in version 3.4.

Applies an expression to each element in an array and combines them into a single value.

`\$reduce` has the following syntax:

Field Type Description
`input` array

Can be any valid expression that resolves to an array. For more information on expressions, see Expressions.

If the argument resolves to a value of `null` or refers to a missing field, `\$reduce` returns `null`.

If the argument does not resolve to an array or `null` nor refers to a missing field, `\$reduce` returns an error.

`initialValue` expression The initial cumulative `value` set before `in` is applied to the first element of the `input` array.
`in` expression

A valid expression that `\$reduce` applies to each element in the `input` array in left-to-right order. Wrap the `input` value with `\$reverseArray` to yield the equivalent of applying the combining expression from right-to-left.

During evaluation of the `in` expression, two variables will be available:

• `value` is the variable that represents the cumulative value of the expression.
• `this` is the variable that refers to the element being processed.

If `input` resolves to an empty array, `\$reduce` returns `initialValue`.

Example Results
`"abc"`
`{ "sum" : 15, "product" : 48 }`
`[ 1, 2, 3, 4, 5, 6 ]`

Examples

Multiplication

Probability

A collection named `events` contains the events of a probability experiment. Each experiment can have multiple `events`, such as rolling a die several times or drawing several cards (without replacement) in succession to achieve a desired result. In order to obtain the overall probability of the experiment, we will need to multiply the probability of each event in the experiment.

Steps:

1. Use `\$group` to group by the `experimentId` and use `\$push` to create an array with the probability of each event.
2. Use `\$reduce` with `\$multiply` to multiply and combine the elements of `probabilityArr` into a single value and project it.

The operation returns the following:

Discounted Merchandise

A collection named `clothes` contains the following documents:

Each document contains a `discounts` array containing the currently available percent-off coupons for each item. If each discount can be applied to the product once, we can calculate the lowest price by using `\$reduce` to apply the following formula for each element in the `discounts` array: (1 - discount) * price.

The operation returns the following: