- Reference >
- Operators >
- Aggregation Pipeline Operators >
- $map (aggregation)
$map (aggregation)¶
On this page
Definition¶
-
$map¶ Applies an expression to each item in an array and returns an array with the applied results.
The
$mapexpression has the following syntax:Field Specification inputAn expression that resolves to an array. asOptional. A name for the variable that represents each individual element of the inputarray. If no name is specified, the variable name defaults tothis.inAn expression that is applied to each element of the inputarray. The expression references each element individually with the variable name specified inas.For more information on expressions, see Expressions.
Examples¶
Add to each element of an array using $map¶
In mongosh, create a sample collection named
grades with the following documents:
The following aggregation operation uses $map with the
$add expression to increment each element in the
quizzes array by 2.
This operation returns the following results:
Truncate each array element with $map¶
In mongosh, create a sample collection named
deliveries with the following documents:
The following aggregation operation uses $map to
truncate each element in the distances array
to its integer.
This operation returns the following results:
Convert Celsius Temperatures to Fahrenheit Using $map¶
In mongosh, create a sample collection named
temperatures with the following documents:
The following aggregation operation uses the $addFields
stage to add a new field to the documents called tempsF which
contains Fahrenheit equivalents of the elements in the tempsC
array. To convert from Celsius to Fahrenheit, the operation uses
$map to $multiply the Celsius
values by 9/5 and then $add 32.
This operation returns the following results: