Navigation

$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:

{ $map: { input: <expression>, as: <string>, in: <expression> } }
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 to this.
in An expression that is applied to each element of the input array. The expression references each element individually with the variable name specified in as.

For more information on expressions, see Expressions.

Example

Consider a grades collection with the following documents:

{ _id: 1, quizzes: [ 5, 6, 7 ] }
{ _id: 2, quizzes: [ ] }
{ _id: 3, quizzes: [ 3, 8, 9 ] }

And the following $project statement:

db.grades.aggregate(
   [
      { $project:
         { adjustedGrades:
            {
              $map:
                 {
                   input: "$quizzes",
                   as: "grade",
                   in: { $add: [ "$$grade", 2 ] }
                 }
            }
         }
      }
   ]
)

The operation returns the following results:

{ "_id" : 1, "adjustedGrades" : [ 7, 8, 9 ] }
{ "_id" : 2, "adjustedGrades" : [ ] }
{ "_id" : 3, "adjustedGrades" : [ 5, 10, 11 ] }

See also

$let