I'm looping a list and inside that loop I'm looping some documents which are fetched from mongodb. But in the output console I can see only one iteration. But the outer loop works fine. When I debug it goes inside the outer loop but doesn't go to the inner loop. Please help me out.
client = MongoClient('mongodb://localhost:27017/')
db = client['mydb']
documents = icps_db.user.find({})
name_set = ['john', 'marshal', 'ann' ...]
for name in name_set:
print(name)
for idx, document in enumerate(documents):
print (documents)
if name in document["filtered_words"]:
print ("Found " + name)
else:
print (name + " not found in document ")
Output In the second iteration it doesn't reach line : print (str(idx)).
john
<pymongo.cursor.Cursor object at 0x7faed0ad0910>
Found john
<pymongo.cursor.Cursor object at 0x7faed0ad0910>
john not found in document
<pymongo.cursor.Cursor object at 0x7faed0ad0910>
Found john
<pymongo.cursor.Cursor object at 0x7faed0ad0910>
john not found in document
<pymongo.cursor.Cursor object at 0x7faed0ad0910>
john not found in document
<pymongo.cursor.Cursor object at 0x7faed0ad0910>
Found john
<pymongo.cursor.Cursor object at 0x7faed0ad0910>
john not found in document
<pymongo.cursor.Cursor object at 0x7faed0ad0910>
Found john
<pymongo.cursor.Cursor object at 0x7faed0ad0910>
Found john
<pymongo.cursor.Cursor object at 0x7faed0ad0910>
john not found in document
john
marshal
marshal
documentsis not empty? Perhaps print this collection first.documentsis probably empty.documents = icps_db.user.find({})After you first set of iterations overdocumentsthe cursor is used up. It's a read-once container. You either need to cache the results or dofind()inside the outer loop. I'm not familiar withmongodb, but a changing the definition ofdocumentstodocuments = list(icps_db.user.find({}))should make your problem go away. The only way that wouldn't work is if each document has some sort of live callback that uses the cursor (which I doubt).documents.rewind()before your inner loop.rewindAccording to the docs this will "Rewind this cursor to its unevaluated state. Reset this cursor if it has been partially or completely evaluated. Any options that are present on the cursor will remain in effect. Future iterating performed on this cursor will cause new queries to be sent to the server, even if the resultant data has already been retrieved by this cursor."