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.
| Category | Cursor |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
db.<collection>.find(<filter>).map(<transform>)
⚙️ Parameters
| transform function | Function 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
- map() consumes the cursor and returns an array
- The transform produces new values; database documents are untouched
- Finish cursor chaining first, then map to an array
🏷️ Related Tags
💡 Related Cases
📚 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.