- 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
$map
expression has the following syntax:Field Specification input
An expression that resolves to an array. as
Optional. A name for the variable that represents each individual element of the input
array. If no name is specified, the variable name defaults tothis
.in
An expression that is applied to each element of the input
array. 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
¶
From the mongo
shell, 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
¶
From the mongo
shell, 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
¶
From the mongo
shell, 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: