0
0
MongodbHow-ToBeginner · 3 min read

How to Use $map in Aggregation in MongoDB

In MongoDB aggregation, use the $map operator to apply an expression to each element of an array and return a new array with the transformed values. It requires specifying the input array, a variable name for each element, and the transformation expression inside $map.
📐

Syntax

The $map operator has three main parts:

  • input: The array to transform.
  • as: A variable name to represent each element in the array.
  • in: The expression to apply to each element.

This creates a new array with each element replaced by the result of the expression.

json
{
  $map: {
    input: <array>,
    as: <variable>,
    in: <expression>
  }
}
💻

Example

This example shows how to double each number in an array field called numbers using $map in an aggregation pipeline.

mongodb
db.collection.aggregate([
  {
    $project: {
      doubledNumbers: {
        $map: {
          input: "$numbers",
          as: "num",
          in: { $multiply: ["$$num", 2] }
        }
      }
    }
  }
])
Output
[ { "doubledNumbers" : [2, 4, 6, 8] }, { "doubledNumbers" : [10, 20, 30, 40] } ]
⚠️

Common Pitfalls

Common mistakes when using $map include:

  • Not using $$ before the variable name inside the in expression (e.g., use $$num not $num).
  • Passing a non-array value to input, which causes errors.
  • Forgetting to use $project or another stage to output the transformed array.
json
/* Wrong: missing $$ before variable */
{
  $map: {
    input: "$numbers",
    as: "num",
    in: { $multiply: ["$num", 2] }  // Incorrect
  }
}

/* Correct: use $$ before variable */
{
  $map: {
    input: "$numbers",
    as: "num",
    in: { $multiply: ["$$num", 2] }  // Correct
  }
}
📊

Quick Reference

PartDescriptionExample
inputArray to transform"$numbers"
asVariable name for each element"num"
inExpression applied to each element{ $multiply: ["$$num", 2] }

Key Takeaways

Use $map to transform each element of an array in aggregation pipelines.
Always prefix the variable with $$ inside the in expression.
Ensure the input is an array to avoid errors.
Use $project or similar stages to output the transformed array.
The $map operator returns a new array with transformed elements.