OPTIONS

$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 The variable name for the items in the input array. The in expression accesses each item in the input array by this variable.
in The expression to apply to each item in the input array. The expression accesses the item by its variable name.

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

Was this page helpful?

Yes No

Thank you for your feedback!

We're sorry! You can Report a Problem to help us improve this page.