> For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt

# $map (expression operator)

## Definition

Applies an [expression](https://www.mongodb.com/docs/manual/reference/mql/expressions.md#std-label-aggregation-expressions) to each item in an array and returns an array with the applied results.

## Compatibility

You can use `$map` for deployments hosted in the following environments:

- [MongoDB Atlas](https://www.mongodb.com/docs/atlas): The fully managed service for MongoDB deployments in the cloud

* [MongoDB Enterprise](https://www.mongodb.com/docs/manual/administration/install-enterprise.md#std-label-install-mdb-enterprise): The subscription-based, self-managed version of MongoDB

* [MongoDB Community](https://www.mongodb.com/docs/manual/administration/install-community.md#std-label-install-mdb-community-edition): The source-available, free-to-use, and self-managed version of MongoDB

## Syntax

The [`$map`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/map.md#mongodb-expression-exp.-map) expression has the following syntax:

```javascript
{
   $map: {
      input: <expression>,
      as: <string>,
      arrayIndexAs: <string>,
      in: <expression>
   }
}
```

| Field | Specification |
| --- | --- |
| `input` | An [expression](https://www.mongodb.com/docs/manual/reference/mql/expressions.md#std-label-aggregation-expressions) that resolves to an array. If `input` resolves to `null` or refers to a missing field, `$map` returns `null`. If `input` resolves to a non-array, non-null value, the pipeline errors. |
| `as` | Optional. A name for the [variable](https://www.mongodb.com/docs/manual/reference/aggregation-variables.md) that represents each individual element of the `input` array. If no name is specified, the variable name defaults to `this`. |
| `arrayIndexAs` | Optional. A name for the [aggregation variable](https://www.mongodb.com/docs/manual/reference/aggregation-variables.md#std-label-aggregation-variables) that represents the index of the current element in the `input` array. The first array element index is `0`. You can use the variable name in an expression. For example, if you specify `arrayIndexAs: "myIndex"`, you use `$$myIndex` in the expression. `$$myIndex` returns the index of the current element in the `input` array. If you omit `arrayIndexAs`, you can use the [`$$IDX`](https://www.mongodb.com/docs/manual/reference/aggregation-variables.md#mongodb-variable-variable.IDX) system variable in the expression to return the index of the current element. For examples, see [Access the Index of Each Item in an Array](https://www.mongodb.com/docs/manual/reference/operator/aggregation/map.md#std-label-map-index-example) and [Use `$$IDX` to Access the Index.](https://www.mongodb.com/docs/manual/reference/operator/aggregation/map.md#std-label-map-IDX-example) **New in version 8.3** |
| `in` | An [expression](https://www.mongodb.com/docs/manual/reference/mql/expressions.md#std-label-aggregation-expressions) 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.](https://www.mongodb.com/docs/manual/reference/mql/expressions.md#std-label-aggregation-expressions)

## Examples

### Add to Each Element of an Array

The examples on this page use data from the [sample\_mflix dataset](https://www.mongodb.com/docs/manual/sample-data/sample-mflix.md#std-label-sample-mflix). For details on how to load this dataset into your self-managed MongoDB deployment, see [Load the Sample Dataset](https://www.mongodb.com/docs/manual/sample-data/load-sample-data-local.md#std-label-sample-dataset-local). If you made any modifications to the sample databases, you may need to drop and recreate the databases to run the examples on this page.

The following aggregation operation uses [`$map`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/map.md#mongodb-expression-exp.-map) with the [`$add`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/add.md#mongodb-expression-exp.-add) expression to add `10` to each element in the `location.geo.coordinates` array:

```javascript
db.theaters.aggregate( [
   {
      $match: {
         theaterId: { $in: [ 1000, 1003, 1008 ] }
      }
   },
   {
      $project: {
         _id: 0,
         theaterId: 1,
         adjustedCoordinates: {
            $map: {
               input: "$location.geo.coordinates",
               as: "coord",
               in: { $add: [ "$$coord", 10 ] }
            }
         }
      }
   },
   { $sort: { theaterId: 1 } }
] )

```

**Output:**

```javascript
[
  { theaterId: 1000, adjustedCoordinates: [ -83.24565, 54.85466 ] },
  { theaterId: 1003, adjustedCoordinates: [ -66.512016, 48.29697 ] },
  { theaterId: 1008, adjustedCoordinates: [ -111.96328, 48.367649 ] }
]

```

### Truncate Each Array Element

The following aggregation operation uses [`$map`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/map.md#mongodb-expression-exp.-map) to [`truncate`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/trunc.md#mongodb-expression-exp.-trunc) each element in the `location.geo.coordinates` array to its integer:

```javascript
db.theaters.aggregate( [
   {
      $match: {
         theaterId: { $in: [ 1000, 1003, 1008 ] }
      }
   },
   {
      $project: {
         _id: 0,
         theaterId: 1,
         integerCoordinates: {
            $map: {
               input: "$location.geo.coordinates",
               as: "coord",
               in: { $trunc: "$$coord" }
            }
         }
      }
   },
   { $sort: { theaterId: 1 } }
] )

```

**Output:**

```javascript
[
  { theaterId: 1000, integerCoordinates: [ -93, 44 ] },
  { theaterId: 1003, integerCoordinates: [ -76, 38 ] },
  { theaterId: 1008, integerCoordinates: [ -121, 38 ] }
]

```

### Apply Arithmetic Operators to Each Array Element

The following aggregation operation uses the [`$addFields`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/addfields.md#mongodb-pipeline-pipe.-addFields) stage to add a new `genreScores` field. The operation uses [`$map`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/map.md#mongodb-expression-exp.-map) to apply [`$multiply`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/multiply.md#mongodb-expression-exp.-multiply) and [`$add`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/add.md#mongodb-expression-exp.-add) to each element in the `genres` array, computing a score based on the character count of each genre name:

```javascript
db.movies.aggregate( [
  {
     $match: { runtime: { $gt: 1000 } }
  },
  {
     $addFields: {
        genreScores: {
           $map: {
              input: "$genres",
              as: "genre",
              in: {
                 $add: [
                    { $multiply: [ { $strLenCP: "$$genre" }, 2 ] },
                    1
                 ]
              }
           }
        }
     }
  },
  { $project: { _id: 0, title: 1, genres: 1, genreScores: 1 } },
  { $sort: { title: 1 } }
] )

```

**Output:**

```javascript
[
  {
    genres: [ 'Documentary', 'History', 'Sport' ],
    title: 'Baseball',
    genreScores: [ 23, 15, 11 ]
  },
  {
    genres: [ 'Action', 'Adventure', 'Drama' ],
    title: 'Centennial',
    genreScores: [ 13, 19, 11 ]
  }
]

```

### Access the Index of Each Item in an Array

The `genres` field in the `movies` collection contains an array of genre names for each movie.

The following example uses `arrayIndexAs`. The `myIndex` variable has the index of each genre in the `genres` array. The example returns documents with these fields:

- Movie title.

- Genre name.

- Position of the genre in the `genres` array in the `rank` field.

- `isPrimary` boolean that is `true` for the first genre in the array, and `false` for the other genres.

```javascript
db.movies.aggregate( [
   {
      $match: { runtime: { $gt: 1000 } }
   },
   {
      $project: {
         _id: 0,
         title: 1,
         rankedGenres: {
            $map: {
               input: "$genres",
               as: "genre",
               arrayIndexAs: "myIndex",
               in: {
                  genre: "$$genre",
                  rank: { $add: [ "$$myIndex", 1 ] },
                  isPrimary: { $eq: [ "$$myIndex", 0 ] }
               }
            }
         }
      }
   },
   { $sort: { title: 1 } }
] )

```

**Output:**

```javascript
[
  {
    title: 'Baseball',
    rankedGenres: [
      { genre: 'Documentary', rank: 1, isPrimary: true },
      { genre: 'History', rank: 2, isPrimary: false },
      { genre: 'Sport', rank: 3, isPrimary: false }
    ]
  },
  {
    title: 'Centennial',
    rankedGenres: [
      { genre: 'Action', rank: 1, isPrimary: true },
      { genre: 'Adventure', rank: 2, isPrimary: false },
      { genre: 'Drama', rank: 3, isPrimary: false }
    ]
  }
]

```

### Use `$$IDX` to Access the Index

The [`$$IDX`](https://www.mongodb.com/docs/manual/reference/aggregation-variables.md#mongodb-variable-variable.IDX) variable returns the index of the current element in the `input` array. You can use `$$IDX` if you omit the `arrayIndexAs` field from the expression.

The following example returns the same documents as the previous example in [Access the Index of Each Item in an Array](https://www.mongodb.com/docs/manual/reference/operator/aggregation/map.md#std-label-map-index-example), but uses `$$IDX` instead of `arrayIndexAs`:

```javascript
db.movies.aggregate( [
   {
      $match: { runtime: { $gt: 1000 } }
   },
   {
      $project: {
         _id: 0,
         title: 1,
         rankedGenres: {
            $map: {
               input: "$genres",
               as: "genre",
               in: {
                  genre: "$$genre",
                  rank: { $add: [ "$$IDX", 1 ] },
                  isPrimary: { $eq: [ "$$IDX", 0 ] }
               }
            }
         }
      }
   },
   { $sort: { title: 1 } }
] )

```

**Output:**

```javascript
[
  {
    title: 'Baseball',
    rankedGenres: [
      { genre: 'Documentary', rank: 1, isPrimary: true },
      { genre: 'History', rank: 2, isPrimary: false },
      { genre: 'Sport', rank: 3, isPrimary: false }
    ]
  },
  {
    title: 'Centennial',
    rankedGenres: [
      { genre: 'Action', rank: 1, isPrimary: true },
      { genre: 'Adventure', rank: 2, isPrimary: false },
      { genre: 'Drama', rank: 3, isPrimary: false }
    ]
  }
]

```

## Learn More

To learn more about expressions used in the previous examples, see:

- [`$add`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/add.md#mongodb-expression-exp.-add)

- [`$multiply`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/multiply.md#mongodb-expression-exp.-multiply)

- [`$trunc`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/trunc.md#mongodb-expression-exp.-trunc)

- [`$strLenCP`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/strlencp.md#mongodb-expression-exp.-strLenCP)
