map() (Transform Cursor)

Last updated: 2026-10-09

map() (Transform Cursor)

map() applies a transform to every document in a cursor and returns the results as an array, e.g. `db.users.find().map(function(u) { return u.name })`. Think forEach() plus result collection — handy for extracting fields or reshaping data. Note that map() consumes the whole cursor and returns an array, not a new cursor.

CategoryCursor
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

db.<collection>.find(<filter>).map(<transform>)

⚙️ Parameters

transform functionFunction mapping a document to a new value, e.g. function(u) { return u.name }.

Returns:Array of transformed values.

▶ Example

Run the commands below in your local mongosh (requires a running mongod):

// map: extract all adult users' names
const names = db.users.find({ age: { $gte: 18 } }).map(u => u.name)
names

Output:

[ 'Alice', 'Bob', 'Cara' ]

📌 Notes

📚 Related Tutorials

❓ FAQ

QWhat is the difference between map and forEach?
Amap() returns an array of transformed values for extraction; forEach() runs a callback and returns nothing.
QIs map's result an array?
AYes, map() returns an array — like forEach plus result collection.
QDoes map modify documents in the database?
ANo — the transform runs on in-memory copies client-side.
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%

🙏 帮我们做得更好

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

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