问题
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