Pymongo 嵌套循环两个游标对象不起作用

Pymongo nested loop two cursor object not working

我可能很笨,但查询结果 userslocations

返回了两个游标对象
    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

内循环用户似乎只执行了一次,而外循环的行为符合预期。

以上代码的输出:

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

如果 locations 是一个游标,它将是一个可迭代对象,而不是列表、数组或字典。会用next遍历,MongoDB游标不提供任何resetrewind.

第一个用户循环后,游标耗尽,后续用户循环立即结束。

您可以尝试在循环之前将游标读入列表,例如

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

您应该能够多次遍历该列表。