pymongo.errors.CursorNotFound: cursor id '...' not valid at server
You're getting this error because the cursor is timing out on the server (after 10 minutes of inactivity).
From the pymongo documentation:
Cursors in MongoDB can timeout on the server if they’ve been open for a long time without any operations being performed on them. This can lead to an CursorNotFound exception being raised when attempting to iterate the cursor.
When you call the collection.find
method it queries a collection and it returns a cursor to the documents. To get the documents you iterate the cursor. When you iterate over the cursor the driver is actually making requests to the MongoDB server to fetch more data from the server. The amount of data returned in each request is set by the batch_size()
method.
From the documentation:
Limits the number of documents returned in one batch. Each batch requires a round trip to the server. It can be adjusted to optimize performance and limit data transfer.
Setting the batch_size to a lower value will help you with the timeout errors errors, but it will increase the number of times you're going to get access the MongoDB server to get all the documents.
The default batch size:
For most queries, the first batch returns 101 documents or just enough documents to exceed 1 megabyte. Batch size will not exceed the maximum BSON document size (16 MB).
There is no universal "right" batch size. You should test with different values and see what is the appropriate value for your use case i.e. how many documents can you process in a 10 minute window.
The last resort will be that you set no_cursor_timeout=True
. But you need to be sure that the cursor is closed after you finish processing the data.
How to avoid it without try/except
:
cursor = collection.find(
{"x": 1},
no_cursor_timeout=True
)
for doc in cursor:
# do something with doc
cursor.close()
You can make the cursor not to timeout by using no_cursor_timeout=True
like this:
cursor=db.images.find({}, {'id':1, 'image_path':1, '_id':0}, no_cursor_timeout=True)
for i in cursor:
# .....
# .....
cursor.close() # use this or cursor keeps waiting so ur resources are used up
Earlier this was referred to as timeout
which has been replaced as per the docs.
For more options on which methods support no_cursor_timeout
refer this search results in pymongo docs.