Variables in Aggregation Expressions
Aggregation expressions can use bothuser-defined and system variables.
Variables can hold any BSON type data.To access the value of the variable, use a string with the variablename prefixed with double dollar signs (); i.e.
"<variable>"
.
If the variable references an object, to access a specific field in theobject, 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:
Variable | Description |
---|---|
- NOW - | A variable the returns the current datetime value.NOW returns the same value for all members of thedeployment and remains the same throughout all stages of theaggregation pipeline.New in version 4.2. |
- CLUSTER_TIME - | A variable that returns the current timestamp value.CLUSTER_TIME is only available on replica sets andsharded clusters.CLUSTER_TIME returns the same value for all membersof the deployment and remains the same throughout all stages ofthe pipeline.New in version 4.2. |
- ROOT - | References the root document, i.e. the top-level document, currentlybeing processed in the aggregation pipeline stage. |
- CURRENT - | References the start of the field path being processed in theaggregation pipeline stage. Unless documented otherwise, allstages start with CURRENT the same asROOT .CURRENT is modifiable. However, since $<field> is equivalent to $$CURRENT.<field> , rebindingCURRENT changes the meaning of $ accesses. |
- REMOVE - | A variable which evaluates to the missing value. Allows for theconditional exclusion of fields. In a $projection , afield set to the variable REMOVE is excluded fromthe output.For an example of its usage, see Conditionally Exclude Fields.New in version 3.6. |
- DESCEND - | One of the allowed results of a $redact expression. |
- PRUNE - | One of the allowed results of a $redact expression. |
- KEEP - | One of the allowed results of a $redact expression. |
See also