jldelda jldelda - 2 months ago 32
Python Question

How to make a for loop in pymongo/python with collections?

How to make a loop iterating over all collections in pymongo?

I have this code:

for index, item in enumerate(list_courses):
bulk_demographics = "db." + item + ".demographics"

for i in bulk_demographics.find({"user_id":1}).limit(1):
print i

"list_courses" contains all the different collection names in my mongo database.

It seems that the error comes from the concat action, because it works perfectly when I paste the name of the collection directly.

This is the error that I get:

TypeError Traceback (most recent call last)
<ipython-input-33-cb93513f793d> in <module>()
1 for index, item in enumerate(list_courses):
2 bulk_demographics = "db." + item + ".demographics"
----> 3 for i in bulk_demographics.find({"user_id":1}).limit(1):
4 print i

TypeError: coercing to Unicode: need string or buffer, dict found


The PyMongo documentation indicates that if you want to access a collection from a PyMongo database using a string that represents its name, you use bracket notation instead of dot notation:

bulk_demographics = db[item].demographics