MongoDB $map Operator

Beginner
5 min read
Updated: Oct 2026
3 examples
Live preview

What Is $map?

$map is a MongoDB aggregation expression that runs an expression on every element of an array and returns a new array of the same length. Like JavaScript’s Array.map(), but inside the pipeline.

Remember
$map = Array.map for aggregation

{
  $map: {
    input: <array>,
    as: "<name>",
    in: <expression using $$name>
  }
}

same length in → same length out
null / missing input → null
non-array input → pipeline error
UsePrefer
Transform every element$map
Keep only matching elements$filter
Collapse array to one value$reduce

How to Use $map in MongoDB

Name each element, then write the expression that builds the new value.

  1. Choose an expression stage ($addFields or $project).
  2. Set input to an array field (or an expression that returns an array).
  3. Set as to a short name (for example "score").
  4. Write in using $$score (double dollar) for the current element.
PieceRequired?Role
inputYesArray to walk
asNoVariable name per element (default: this)
inYesExpression that becomes each new item

Pseudocode

Pseudocode
for each document:
    arr = evaluate(input)
    if arr is null or missing:
        result = null
    else if arr is not an array:
        error  // aggregation fails
    else:
        result = []
        for each item in arr:
            bind as-name → item
            result.push( evaluate(in) )
    emit { ..., field: result }

Cheat Sheet

Keep these facts handy while writing array transforms.

TopicDetail
TypeAggregation expression (not a find filter)
Syntax{ $map: { input, as, in } }
Current item$$<as> (example: $$score)
Default nameOmit as → use $$this
LengthOutput length = input length
Null inputReturns null
vs $filterMap transforms; filter selects

Live Preview

Watch $map transform every score. Pick a transform, then run.

Simulates $map on scores: [8, 7, 9] (same idea as the mongosh examples below).

Result
input = [8, 7, 9]
in = $$score + 5

$map → [13, 12, 14]

{ adjusted: [13, 12, 14] }

Worked Walkthrough — Add Bonus Points

Quiz scores are stored as [8, 7, 9]. We add 5 bonus points to each score with $map.

Calculation
Document:
  { name: "Ada", scores: [8, 7, 9] }

$map walks the array:
  $$score = 8 → 8 + 5 = 13
  $$score = 7 → 7 + 5 = 12
  $$score = 9 → 9 + 5 = 14

Result:
  adjusted: [13, 12, 14]

Same length: 3 in → 3 out ✓

MongoDB Examples

We use a small quizzes collection. First we add a bonus to each score, then scale scores to a 0–100 range. Run these in mongosh after inserting the sample data once.

Example 1 — Sample Data

Imagine two students. Each has a name and an array of quiz scores out of 10. We save them in a collection named quizzes.

mongosh
db.quizzes.insertMany([
  { _id: 1, name: "Ada", scores: [8, 7, 9] },
  { _id: 2, name: "Grace", scores: [6, 8, 7] }
]);

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps two documents in quizzes. Run find() to see them:

mongosh
db.quizzes.find()

Read one document like this:

Field in MongoDBValue (Ada)Plain English
_id1Document id
name"Ada"Student name
scores[8, 7, 9]Quiz scores out of 10

How It Works

  1. Insert once. insertMany adds two student documents to quizzes.
  2. scores is an array. Each number is one quiz result—ready for $map.
  3. find() shows the same shape. What you inserted is what you get back.

Example 2 — Add to Each Element

Goal: add 5 bonus points to every score using $map and $add.

mongosh
db.quizzes.aggregate([
  {
    $addFields: {
      adjusted: {
        $map: {
          input: "$scores",
          as: "score",
          in: { $add: ["$$score", 5] }
        }
      }
    }
  }
]);

How It Works

  1. Read the array. input: "$scores" gives [8, 7, 9] for Ada.
  2. Name each item. as: "score" means the current number is $$score.
  3. Transform. $add runs $$score + 5 for every element.
  4. New field. $addFields stores the result in adjusted; original scores stay.

Example 3 — Scale Each Element

Same quizzes, but convert scores out of 10 into a 0–100 scale by multiplying each score by 10.

mongosh
db.quizzes.aggregate([
  {
    $addFields: {
      percent: {
        $map: {
          input: "$scores",
          as: "score",
          in: { $multiply: ["$$score", 10] }
        }
      }
    }
  }
]);

How It Works

  1. Same stored arrays. Still using Ada’s [8, 7, 9] and Grace’s [6, 8, 7].
  2. Same $map shape. input + as + in—only the math changes.
  3. Multiply each item. $multiply turns 8 into 80, 7 into 70, and so on.
  4. Easy check. Out of 10 × 10 = percent. Three scores in → three percents out.

Edge Cases & Pitfalls

Check these before using $map in production pipelines.

$$

Use double dollar for the item

Inside in, write $$score (not $score). A single $ looks for a document field named score.

type

input must be an array

A number or string makes the pipeline fail. Null or missing returns null.

length

$map does not drop items

To remove elements, use $filter. $map always keeps the same count.

as

Pick a clear as name

Avoid names that clash with fields you also read as $field. Short names like score or item stay readable.

Performance Notes

ApproachCostBest for
$map aloneO(docs × array length)Simple per-element math
$map + nested opsSame order, heavier inMulti-step transforms per item
$filter then $mapOften cheaper overallTransform only matching items

Cost grows with array size. Filter early with $match when only some documents need a transform, and keep in expressions small.

Key Takeaways

  • Role: transform every array element → new array.
  • Shape: input + as + in.
  • Variable: current item is $$name.
  • Not filter: use $filter to drop items.

One line: $map answers “what should each array item become?”—same length in, same length out.

Frequently Asked Questions

$map applies an expression to every element in an array and returns a new array with the transformed values. Same length as the input. Think of it as Array.map() for aggregation.
The syntax is { $map: { input: <array>, as: <string>, in: <expression> } }. input is the array, as names each element, and in is the expression run once per element.
Use the name from as with a double-dollar prefix. If as is "score", write "$$score" inside in. If you omit as, the default variable is $$this.
$map transforms every element and keeps the same length. $filter keeps only elements that pass a condition, so the result may be shorter.
$map returns null. If input is a non-array, non-null value, the aggregation fails with an error.
Yes for the idea. Think of $map as MongoDB’s aggregation version of Array.map—run it in the pipeline, not as a standalone find() filter.

Next: $meta

Read aggregation metadata such as text search scores.

$meta tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

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.

9 people found this page helpful