$map (Transform Array Elements)
Last updated: 2026-10-09
$map (Transform Array Elements)
$map iterates an array, passes every element through the in expression, and collects the results into a new array of the same length. It is the most used functional operator in aggregation expressions. Typical cases: applying tax to every order item, uppercasing a list of strings, or extracting a field from an array of objects. The as variable is referenced as $$variable inside in, or use $$this when as is omitted. $map keeps the length and changes element values; combine with $filter (removal) and $reduce (folding) for full array pipelines.
| Category | Array |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $map: { input: <array>, as: <variable>, in: <expression> } }
⚙️ Parameters
| input | The array to iterate. |
|---|---|
| as | The variable name for the current element, referenced as $$variable in in; optional, defaults to $$this. |
| in | The expression evaluated for each element; its results form the new array. |
Returns:A new array of in results per element; null if input is null
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $map: double each item quantity
db.orders.aggregate([
{ $project: {
doubled: { $map: { input: '$items', as: 'it', in: { $multiply: ['$$it.qty', 2] } } }
} }
])
Output:
{ '_id': 1, 'doubled': [ 4, 6 ] }
{ '_id': 2, 'doubled': [ 2 ] }
📌 Notes
- in is the final expression per element; reference the as variable with a $$ prefix
- $map preserves length: it changes values, not count; remove elements with $filter
- Nest $map/$filter/$reduce inside in to build functional pipelines
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QWhat is the difference between $map and $filter?
A$map transforms every element without changing length; $filter removes elements without changing content. They nest well.
QCan $map change the array length?
ANo, the result matches the input length. Use $filter or $reduce to change it.
QCan I omit the as variable?
AYes — reference the current element with $$this in in when omitted.