Home > Software engineering >  Pymongo nested loop two cursor object not working
Pymongo nested loop two cursor object not working

Time:10-28

I might be dumb but I have two cursor objects returned by query result users and locations

    user_count = 0
    location_count = 0
    for user in users:
        print(user)  ## prints every object correctly
        user_count = user_count   1
        for location in locations:
            print(location) ##only loops once on the first user
            location_count = location_count   1

    print(user_count, location_count)   ## 1720 39

the inner loop user seems only executed once while the outer loop behaves as expected.

the output of the above code:

#prints the first user
#prints all locations 
#prints all remaining users
! missing locations

CodePudding user response:

If locations is a cursor, it will be an iterable, not a list, array, or dict. It will be traversed with next, and MongoDB cursors do not provide any reset or rewind.

After it loops through for the first user, the cursor is exhausted, so for the subsequent users the loop ends immediately.

You might try reading the cursor into a list before the loop, like

locations = list(db.collection.find())

The you should be able to loop over that list multiple times.

  • Related