- Reference >
- Operators >
- Aggregation Pipeline Operators >
- $accumulator (aggregation)
$accumulator (aggregation)¶
On this page
Definition¶
-
$accumulator¶ New in version 4.4.
Defines a custom accumulator operator. Accumulators are operators that maintain their state (e.g. totals, maximums, minimums, and related data) as documents progress through the pipeline. Use the
$accumulatoroperator to execute your own JavaScript functions to implement behavior not supported by the MongoDB Query Language. See also$function.Important
Executing JavaScript inside of an aggregation operator may decrease performance. Only use the
$accumulatoroperator if the provided pipeline operators cannot fulfill your application’s needs.$accumulatoris available in the following pipeline stages:
Syntax¶
The $accumulator operator has the following syntax:
| Field | Type | Description |
|---|---|---|
| init | String or Code | Function used to initialize the state. The The |
| initArgs | Array | Optional. Arguments passed to the
Important When used in a |
| accumulate | String or Code | Function used to accumulate documents. The The |
| accumulateArgs | Array | Arguments passed to the
|
| merge | String or Code | Function used to merge two internal states. The |
| finalize | String or Code | Optional. Function used to update the result of the accumulation. The |
| lang | String | The language used in the Important Currently, the only supported value for |
Behavior¶
The following steps outline how the $accumulator operator
processes documents:
- The operator begins at an initial state, defined by the init function.
- For each document, the operator updates the state based on the accumulate function. The accumulate function’s first argument is the current state, and additional arguments are be specified in the accumulateArgs array.
- When the operator needs to merge multiple intermediate states, it executes the merge function. For more information on when the merge function is called, see Merge Two States with $merge.
- If a finalize function has been defined, once all documents have been processed and the state has been updated accordingly, finalize converts the state to a final output.
Merge Two States with $merge¶
As part of its internal operations, the $accumulator operator
may need to merge two separate, intermediate states. The merge function specifies how the operator should merge
two states.
For example, $accumulator may need to combine two states when:
$accumulatoris run on a sharded cluster. The operator needs to merge the results from each shard to obtain the final result.A single
$accumulatoroperation exceeds its specified memory limit. If you specify theallowDiskUseoption, the operator stores the in-progress operation on disk and finishes the operation in memory. Once the operation finishes, the results from disk and memory are merged together using the merge function.See also
Note
The merge function always merges two states at a time. In the event that more than two states must be merged, the resulting merge of two states is merged with a single state. This process repeats until all states are merged.
Javascript Enabled¶
To use $accumulator, you must have server-side scripting
enabled.
If you do not use $accumulator (or $function,
$where, or mapReduce), disable server-side
scripting:
For a
mongodinstance, seesecurity.javascriptEnabledconfiguration option or--noscriptingcommand-line option.For a
mongosinstance, seesecurity.javascriptEnabledconfiguration option or the--noscriptingcommand-line option starting in MongoDB 4.4.In earlier versions, MongoDB does not allow JavaScript execution onmongosinstances.
Examples¶
Use $accumulator to Implement the $avg Operator¶
Note
This example walks through using the $accumulator operator
to implement the $avg operator, which is already supported
by MongoDB. The goal of this example is not to implement new
functionality, but to illustrate the behavior and syntax of the
$accumulator operator with familiar logic.
From the mongo shell, create a sample collection named
books with the following documents:
The following operation groups the documents by
author, and uses $accumulator to compute the average
number of copies across books for each author:
Result¶
This operation returns the following result:
Behavior¶
The $accumulator defines an initial state where count
and sum are both set to 0. For each document that the
$accumulator processes, it updates the state by:
- Incrementing the
countby 1 and - Adding the values of the document’s
copiesfield to thesum. The accumulate function can access thecopiesfield because it is passed in the accumulateArgs field.
With each document that is processed, the accumulate function returns the updated state.
Once all documents have been processed, the
finalize function divides the sum of
the copies by the count of documents to obtain the average. This
removes the need to keep a running computed average, since the
finalize function receives the cumulative
sum and count of all documents.
Use initArgs to Vary the Initial State by Group¶
You can use the initArgs option in
to vary the initial state of $accumulator. This can be
useful if you want to, for example:
- Use the value of a field which is not in your state to affect your state, or
- Set the initial state to a different value based on the group being processed.
From the mongo shell, create a sample collection named
restaurants with the following documents:
Suppose an application allows users to query this data to find
restaurants. It may be useful to show more results for
the city where the user lives. For this example, we assume that the
user’s city is called in a variable called userProfileCity.
The following aggregation pipeline groups the
documents by city. The operation uses the $accumulator
to display a different number of results from each city depending on
whether the restaurant’s city matches the city in the user’s profile:
Note
To execute this example in the mongo shell, replace
<userProfileCity> in the initArgs
with a string containing an actual city value, such as Bettles.
Results¶
If the value of userProfileCity is Bettles, this operation
returns the following result:
If the value of userProfileCity is Onida, this operation
returns the following result:
If the value of userProfileCity is Pyote, this operation
returns the following result:
If the value of userProfileCity is any other value, this operation
returns the following result:
Behavior¶
The init function defines an initial state
containing max and restaurants fields. The max field sets
the maximum number of restaurants for that particular group. If the
document’s city field matches userProfileCity, that group
contains a maximum of 3 restaurants. Otherwise, if the document _id
does not match userProfileCity, the group contains at most a single
restaurant. The init function receives both
the city userProfileCity arguments from the initArgs array.
For each document that the $accumulator processes, it pushes
the name of the restaurant to the restaurants array, provided
that name would not put the length of restaurants over the max
value. With each document that is processed, the accumulate function returns the updated state.
The merge function defines how to merge two
states. The function concatenates the restaurant arrays from each
state together, and the length of the resulting array is limited using
the slice()
method to ensure that it does not exceed the max value.
Once all documents have been processed, the finalize function modifies the resulting state to only
return the names of the restaurants. Without this function, the max
field would also be included in the output, which does not fulfill any
needs for the application.