The “cursor not found” error in MongoDB typically occurs during data retrieval with cursors, and it means the server killed the cursor before the client finished reading all documents.
⚠️ Common Error Message
🔍 Why This Happens
Here are the main causes:
1. Cursor Timed Out
MongoDB automatically kills idle cursors after 10 minutes (600 seconds) of inactivity.
2. Client Reading Too Slowly
If the client opens a cursor and waits too long (e.g., network lag or slow processing), the cursor may be closed server-side.
3. Connection Issues
If the client loses connection or restarts during an active cursor session, the cursor is lost.
4. Killed by Server
Cursors can be killed manually, or due to memory pressure or server conditions.
5. Cursor Exhausted
If the client attempts to fetch more data after the cursor is exhausted (i.e., all data has been read), this error can sometimes appear.
✅ How to Fix It
🛠 1. Use .noCursorTimeout()
(with caution)
If you expect to hold a cursor open for a long time:
This prevents MongoDB from automatically closing it.
BUT: You must close it manually when done using .close()
to avoid memory leaks.
🛠 2. Fetch Data in Batches Quickly
Make sure your app:
-
Processes documents as they are received
-
Doesn’t leave cursors open or idle for long periods
🛠 3. Use batchSize
to Control Load
Lower batch sizes help avoid long idle periods:
Or use this in aggregation:
🛠 4. Handle Cursor Exceptions Gracefully
Wrap cursor-based reads in try/catch
and reconnect logic:
🛠 5. Avoid Long Client-Side Blocking
Don’t pause between .next()
calls or block while a cursor is open.
🧪 Extra: For Aggregation Pipelines
Use allowDiskUse
and smaller batch sizes to avoid memory-related cursor closures:
🚫 When Not to Use .noCursorTimeout()
-
On short queries
-
In high-load systems without strict resource cleanup
-
When using long-lived scripts without
.close()
✅ Summary
Cause | Fix |
---|---|
Cursor timeout | Use .noCursorTimeout() carefully |
Slow client processing | Process data in real time |
Large batches | Use batchSize() to break it up |
Server pressure / disconnection | Add retry logic, reconnect |
Exhausted cursor | Ensure correct loop and closing |