$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.

CategoryArray
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

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

⚙️ Parameters

inputThe array to iterate.
asThe variable name for the current element, referenced as $$variable in in; optional, defaults to $$this.
inThe 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

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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏