tryNext() (Try Fetching Next Document)
Last updated: 2026-10-09
tryNext() (Try Fetching Next Document)
tryNext() attempts to return the next cursor document, yielding null instead of throwing at the end: `const doc = db.users.find().tryNext()`. Unlike next(), which errors when exhausted, tryNext() keeps iteration code safe and concise — great for conditional loops and fault-tolerant reads.
| Category | Cursor |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
db.<collection>.find(<filter>).tryNext()
Returns:The next document; null when the cursor is exhausted.
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// tryNext: safe iteration without hasNext
const cursor = db.users.find()
let doc
while ((doc = cursor.tryNext()) !== null) {
print(doc.name)
}
Output:
Alice
Bob
Cara
📌 Notes
- Returns null at the end instead of throwing
- Can replace the hasNext()+next() pairing
- Stop anytime by breaking out of the loop
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QWhat is the difference between tryNext and next?
AAt the end, next() throws while tryNext() returns null — the latter iterates more safely.
QCan tryNext replace hasNext?
AYes — the while ((doc = cursor.tryNext()) !== null) pattern iterates safely without hasNext().
QDoes tryNext returning null mean the end?
AYes — null signals the cursor is exhausted and the loop should stop.