MongoDB $map Operator

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 4 Examples
Arrays

What You’ll Learn

The $map operator applies an expression to every element in an array and returns a new array of transformed values. It is MongoDB’s aggregation version of JavaScript’s Array.map().

01

Transform Arrays

Map each element.

02

Syntax

input + as + in.

03

$$ Variable

Current element ref.

04

Same Length

One output per input.

05

Use Cases

Scores, prices, names.

06

vs $filter

Transform vs select.

Definition and Usage

In MongoDB’s aggregation framework, the $map operator loops through an array and evaluates an expression for each element. You provide the source array (input), a variable name (as), and the transformation (in). The results are collected into a new array with the same number of elements as the input.

For example, doubling each score in [70, 85, 90] produces [140, 170, 180]. When the array holds objects, you can extract or reshape fields from each item.

💡
Beginner Tip

Inside in, reference the current array element with a double dollar sign: if as is "score", use "$$score". A single $ refers to document fields; $$ refers to variables defined in $map, $filter, or $let.

📝 Syntax

The $map operator takes an object with input, as, and in:

mongosh
{
  $map: {
    input: <array expression>,
    as: <string>,
    in: <expression>
  }
}

Common Patterns

mongosh
// Double each number
{ $multiply: [ "$$score", 2 ] }

// Extract a field from objects
"$$item.name"

// Add tax to each price
{ $multiply: [ "$$item.price", 1.1 ] }

// Build a new object per element
{ name: "$$item.name", total: {
    $multiply: [ "$$item.qty", "$$item.price" ]
}}

Syntax Rules

  • input — the array to transform (field path like "$scores" or a literal array).
  • as — variable name for the current element (e.g. "item" or "score").
  • in — expression evaluated per element; its result becomes the next output array item.
  • Output array length always matches input array length.
  • If input is null or missing, $map returns null.
  • Use inside stages like $project, $addFields, or $set.

💡 $map vs $filter

$map → transforms every element; output length = input length
$filter → keeps only elements where cond is true; output may be shorter
Analogy$map = array.map(), $filter = array.filter()

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation array expression operator
Syntax{ $map: { input, as, in } }
InputArray or array expression
OutputTransformed array (same length, or null)
Common stages$project, $addFields, $set
Numbers
{
  $map: {
    input: "$scores",
    as: "s",
    in: {
      $multiply: ["$$s", 2]
    }
  }
}

Double each score

Objects
{
  $map: {
    input: "$items",
    as: "item",
    in: "$$item.name"
  }
}

Extract names

Literal
{
  $map: {
    input: [1, 2, 3],
    as: "n",
    in: {
      $add: ["$$n", 10]
    }
  }
}

Returns [11,12,13]

Null input
{
  $map: {
    input: null,
    as: "x",
    in: "$$x"
  }
}

Returns null

Examples Gallery

Walk through a students collection and transform array fields with $map step by step.

📚 Student Scores

Start with a scores array of numbers and double each value with $project.

Sample Input Documents

Suppose you have a students collection:

mongosh
[
  {
    "_id": ObjectId("609c26812e9274a86871bc6a"),
    "name": "Alice",
    "scores": [70, 85, 90]
  },
  {
    "_id": ObjectId("609c26812e9274a86871bc6b"),
    "name": "Bob",
    "scores": [60, 75, 80]
  },
  {
    "_id": ObjectId("609c26812e9274a86871bc6c"),
    "name": "Charlie",
    "scores": [88, 92, 95],
    "grades": [
      { "subject": "Math", "score": 88 },
      { "subject": "Science", "score": 92 }
    ]
  }
]

Example 1 — Double Each Score

Multiply every element in scores by 2:

mongosh
db.students.aggregate([
  {
    $project: {
      name: 1,
      doubledScores: {
        $map: {
          input: "$scores",
          as: "score",
          in: { $multiply: [ "$$score", 2 ] }
        }
      }
    }
  }
])

How It Works

  • MongoDB loops through each element in scores.
  • For each element, $$score holds the current value.
  • in evaluates { $multiply: [ "$$score", 2 ] } and appends the result to the output array.
  • Output length matches input length — three scores in, three doubled values out.

📈 Arrays of Objects

Extract fields and build new structures from object arrays.

Example 2 — Extract Subject Names from grades

Map an array of grade objects to a flat list of subject names:

mongosh
db.students.aggregate([
  {
    $project: {
      name: 1,
      subjects: {
        $map: {
          input: "$grades",
          as: "grade",
          in: "$$grade.subject"
        }
      }
    }
  }
])

How It Works

When array elements are objects, use dot notation on the $$ variable: "$$grade.subject" reads the subject field from each grade object.

Example 3 — Build Pass/Fail Labels per Score

Transform each score into a pass or fail string using $cond inside in:

mongosh
db.students.aggregate([
  {
    $project: {
      name: 1,
      results: {
        $map: {
          input: "$scores",
          as: "score",
          in: {
            $cond: [
              { $gte: [ "$$score", 70 ] },
              "pass",
              "fail"
            ]
          }
        }
      }
    }
  }
])

How It Works

The in expression can be any valid aggregation expression — including $cond, $multiply, or nested objects. Each element gets its own transformed value.

Example 4 — Compute Line Totals from Order Items

Map each item object to its quantity × price total:

mongosh
db.orders.aggregate([
  {
    $project: {
      orderId: 1,
      lineTotals: {
        $map: {
          input: "$items",
          as: "item",
          in: {
            $multiply: [
              "$$item.qty",
              "$$item.price"
            ]
          }
        }
      }
    }
  }
])

// items: [
//   { name: "Pen", qty: 2, price: 5 },
//   { name: "Book", qty: 1, price: 20 }
// ]
// → lineTotals: [10, 20]

How It Works

$map is ideal for per-item calculations inside embedded arrays. Pair with $sum on the result array to get an order total.

Bonus — $map on a Literal Array

You can map over a fixed array without reading from a field:

mongosh
db.students.aggregate([
  {
    $project: {
      incremented: {
        $map: {
          input: [1, 2, 3],
          as: "n",
          in: { $add: [ "$$n", 10 ] }
        }
      }
    }
  }
])

How It Works

input can be a literal array. Every document gets the same result: [11, 12, 13]. Useful for testing expressions or building fixed output structures.

🚀 Use Cases

  • Numeric transforms — scale, round, or convert values in score or measurement arrays.
  • Field extraction — pull one property from each object in an embedded array.
  • Label generation — map raw values to pass/fail, tier, or status strings.
  • Line-item math — compute per-item totals before summing with $sum.

🧠 How $map Works

1

MongoDB reads the input array

The input expression resolves to an array from a field path or literal.

Input
2

Loops with as variable

Each element is bound to $$asName while the in expression runs.

Loop
3

Collects transformed values

Each in result is appended to a new output array in the same order.

Output
=

Transformed array

You get a new array with one transformed value per input element.

Conclusion

The $map operator brings JavaScript-style array mapping into MongoDB aggregation pipelines. Use it to transform every element in an embedded array — scaling numbers, extracting fields, or building new objects — without unwinding documents.

Remember the pattern: input (the array), as (variable name), in (transformation). Reference elements with $$name. When you only need a subset of elements, use $filter instead.

💡 Best Practices

✅ Do

  • Use meaningful as names like item or score
  • Reference elements with $$varName inside in
  • Use $map when every element needs transformation
  • Combine with $sum after mapping line totals
  • Handle missing arrays — null input returns null

❌ Don’t

  • Use $map when you only need matching elements (use $filter)
  • Use single $ for loop variables (use $$)
  • Use $map as a pipeline stage — it is an expression operator
  • Expect output length to differ from input (it stays the same)
  • Forget $unwind is different — it expands documents, not arrays in place

Key Takeaways

Knowledge Unlocked

Five things to remember about $map

Use these points when transforming arrays in MongoDB.

5
Core concepts
📝 02

input + in

Array + expression.

Syntax
🔢 03

$$ Reference

Current element var.

Variables
🛠 04

Same Length

1:1 input/output.

Behavior
📑 05

vs $filter

Map vs select.

Compare

❓ Frequently Asked Questions

$map applies an expression to every element in an array and returns a new array with the transformed values. It is like JavaScript's Array.map() inside an aggregation expression.
The syntax is { $map: { input: <array>, as: <string>, in: <expression> } }. The in expression runs once per element and its result becomes the next item in the output array.
Use the variable name you set in as with a double dollar prefix. If as is "item", reference the current element as "$$item" inside in.
$map transforms every element and keeps the same array length. $filter keeps only elements where a condition is true, so the output array may be shorter.
Use $map inside expression stages such as $project, $addFields, and $set when you need to transform values in an embedded array without changing the parent document count.

Continue the Operator Series

Move on to $meta for text search metadata, or review $filter for selecting array elements.

Next: $meta →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful