Amila Iddamalgoda
Amila Iddamalgoda

Reputation: 4286

Python for each loop is not working

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

Upvotes: 1

Views: 1310

Answers (1)

Steven Rumbalski
Steven Rumbalski

Reputation: 45542

The problem is here:

documents = icps_db.user.find({}) 

After you first set of iterations over documents the cursor is used up. It's a read-once container. You either need to cache the results or do do documents.rewind() before your inner loop.

To cache the results do:

documents = list(icps_db.user.find({})) 

I don't really know MongoDB, so it's possible that each document has some sort of live callback that uses the cursor (I doubt it). If so, simple caching won't work.

The other solution would be to use rewind():

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.

Use it like so:

for name in name_set:
    documents.rewind()
    for idx, document in enumerate(documents):
        ...

Upvotes: 2

Related Questions