Variables in Aggregation Expressions

On this page

Aggregation expressions can use both user-defined and system variables.

Variables can hold any BSON type data. To access the value of the variable, use a string with the variable name prefixed with double dollar signs ( $$ ).

If the variable references an object, to access a specific field in the object, use the dot notation; i.e. "$$<variable>.<field>" .

User Variables

User variable names can contain the ascii characters [_a-zA-Z0-9] and any non-ascii character.

User variable names must begin with a lowercase ascii letter [a-z] or a non-ascii character.

System Variables

MongoDB offers the following system variables:

VariableDescription
ROOTReferences the root document, i.e. the top-level document, currently being processed in the aggregation pipeline stage.
CURRENTReferences the start of the field path being processed in the aggregation pipeline stage. Unless documented otherwise, all stages start with CURRENT the same as ROOT.
CURRENT is modifiable. However, since $<field> is equivalent to $$CURRENT.<field> , rebinding CURRENT changes the meaning of $ accesses.
REMOVEA variable which evaluates to the missing value. Allows for the conditional exclusion of fields. In a $projection , a field set to the variable REMOVE is excluded from the output.
For an example of its usage, see Conditionally Exclude Fields.
New in version 3.6.
DESCENDOne of the allowed results of a $redact expression.
PRUNEOne of the allowed results of a $redact expression.
KEEPOne of the allowed results of a $redact expression.

See also