当前位置: 动力学知识库 > 问答 > 编程问答 >

python - How to get rid of cursor id error in mongodb?

问题描述:

I have tried the following command in pymongo:

records= db.collection_name.find({"gender":"female"}).batch_size(5)

but after a few iterations is gives:

pymongo.errors.CursorNotFound: Cursor not found, cursor id: 61593385827.

Also if I try timeout=False in the same command i.e

records= db.collection_name.find({"gender":"female"},timeout=False).batch_size(5)

its gives

TypeError: __init__() got an unexpected keyword argument 'timeout' error.

网友答案:

Try setting no_cursor_timeout=True in the query, like so:

records= db.collection_name.find({"gender":"female"}, no_cursor_timeout=True).batch_size(5)

网友答案:

Please show more of your code. I suspect the you cursor is just expired.

As described in mongodb manual

By default, the server will automatically close the cursor after 10 minutes of inactivity or if client has exhausted the cursor.

This means, after you created the cursor records and exhausted it by using once, for example, like

mylist = [ i for i in records]

your records cursor does not exist anymore

See also this and this questions

网友答案:

Setting timeout=False is a very bad practice. A better way to get rid of the cursor id timeout exception is to estimate how many documents your loop can process within 10 minutes, and come up with an conservative batch size. This way, the MongoDB client (in this case, PyMongo) will have to query the server once in a while whenever the documents in the previous batch were used up. This will keep the cursor active on the server, and you will still be covered by the 10-minute timeout protection.

Here is how you set batch size for a cursor:

for doc in coll.find().batch_size(30):
    do_time_consuming_things()
分享给朋友:
您可能感兴趣的文章:
随机阅读: