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 theinexpression (e.g., use$$numnot$num). - Passing a non-array value to
input, which causes errors. - Forgetting to use
$projector 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
| Part | Description | Example |
|---|---|---|
| input | Array to transform | "$numbers" |
| as | Variable name for each element | "num" |
| in | Expression 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.