Using pymongo's ReplicaSetConnection: sometimes getting “IndexError: no such item for Cursor”

旧巷老猫 提交于 2019-12-23 03:39:14

问题


I started using pymongo's (version 2.2.1) ReplicaSetConnection object instead of the pymongo.Connection object. Now, when I perform reads from the database, like:

if cur.count() == 0:
    raise NoDocumentsFound(self.name, self.COLLECTION_NAME)
elif cur.count() > 1:
    raise TooManyDocumentsFound(self.name, self.COLLECTION_NAME)

cur.rewind()
rec = cur[0]

I sometimes receive an "IndexError: no such item for Cursor instance" on the final line. From all I can find out about this error, it should occur only when you don't have any records that match your query. However, I've clearly already checked that my cursor has items in it. Is there something odd going on with the ReplicaSetConnection which makes these read operations more volatile?


回答1:


Oh, I'm an idiot. It turned out I had another thread running some test code at the same time. Therefore, there was a concurrent process which had modified the database in the span of time it took for me to examine the cursor and then pull the data out of it.

This is an interesting example of how the cursor is lazy and that the cursor object itself is not just a simple array.

Cheers, --Peter



来源:https://stackoverflow.com/questions/12060402/using-pymongos-replicasetconnection-sometimes-getting-indexerror-no-such-ite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!