forEach() (Iterate Cursor)
Last updated: 2026-10-09
forEach() (Iterate Cursor)
forEach() runs a callback on every document in a cursor, e.g. `db.users.find().forEach(function(doc) { print(doc.name) })`. It processes as it pulls, never buffering everything into memory like toArray(), making it the stream-friendly choice for large result sets. The callback can collect, tally, or log — a staple for batch jobs.
| Category | Cursor |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
db.<collection>.find(<filter>).forEach(<callback>)
⚙️ Parameters
| callback | Function receiving each document, e.g. function(doc) { print(doc.name) }. |
|---|
Returns:undefined (callbacks run over the server document stream).
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// forEach: count adults while streaming
let n = 0
db.users.find({ age: { $gte: 18 } }).forEach(doc => {
n++
})
print(n)
Output:
Alice
Bob
Processed: 2
📌 Notes
- Callbacks run client-side, once per document
- Memory stays flat — ideal for large result sets
- Do not modify the collection being iterated inside the callback; it can loop forever
🏷️ Related Tags
💡 Related Cases
📚 Related Tutorials
❓ FAQ
QWhich uses less memory, forEach or toArray?
AforEach() processes as it pulls with low memory; toArray() loads everything into memory, costlier on big sets.
QCan the forEach callback modify documents?
AThe callback receives a copy — edits do not persist; call update operations inside the callback to write changes.
QCan I break out of forEach early?
AforEach has no break; for conditional exits, loop manually with next() or truncate with limit() first.