The error “cursor not found” in MongoDB typically occurs when a query or cursor is inactive, expired, or invalidated before data retrieval is complete.
🔍 What Does “Cursor Not Found” Mean?
A cursor in MongoDB is a pointer to the result set of a query. The error:
cursor not found
means:
-
The cursor was killed or timed out on the server before all results were read.
-
A subsequent
getMore
operation failed because the cursor no longer exists.
🧯 Common Causes and Fixes
✅ 1. Cursor Timed Out on Long Operations
By default, server-side cursors expire after 10 minutes of inactivity.
✅ Fix:
Use a no-timeout cursor if the operation takes a long time:
Shell:
Driver (Node.js example):
🧠 Reminder: Close the cursor manually when done to avoid memory leaks:
✅ 2. Network Drop or Client Disconnect
If the client disconnects (e.g., due to a crash or timeout), the server may clean up the cursor.
✅ Fix:
-
Retry the query with a new cursor.
-
Use a more stable network or shorter fetch operations.
✅ 3. Using batchSize
Too Large
A large batchSize
can delay responses or overwhelm memory, leading to timeouts.
✅ Fix:
Set a reasonable batchSize
:
✅ 4. Using awaitData
or Tailable Cursors Incorrectly
Tailable cursors (on capped collections) can return this error if not managed correctly.
✅ Fix:
-
Make sure you're using them only on capped collections.
-
Ensure your application logic handles
null
or no-data responses gracefully.
✅ 5. Cursor Already Exhausted
If you try to fetch from a cursor that's already been fully iterated, MongoDB will return this error.
✅ Fix:
Don’t reuse a cursor after it's closed or done:
✅ Best Practices
Tip | Why It Helps |
---|---|
Use .noCursorTimeout() carefully | Prevents auto-timeout but must be closed manually |
Set batchSize appropriately | Improves performance and avoids overload |
Use pagination (skip/limit) if possible | Reduces cursor usage for large sets |
Monitor server logs | Check for cursor timeouts and resource limits |
🧠 Summary
-
Use
.noCursorTimeout()
if query takes long -
Set appropriate
batchSize
-
Retry safely on client/network error
-
Don’t reuse exhausted cursors
-
Use logging and monitoring to diagnose root causes