How to iterate multiple Pymongo query filters with different values

时间:2019-05-06 11:26:03

标签: mongodb pymongo

I have a need to query multiple times, with different values but the same query template.
I thought of doing the following:

industry_list = [
    "Alcoholic Drinks",
    "Apparel and Footwear",
    "Automotive",
    "Baby",
    "Beauty and Personal Care",
    "Consumer Electronics"]

query_filter = "{{ 'sentences': {{'$exists': True}}, 'rank': 0, 'industry': '{}' }}"

for industry in industry_list:
    industry_query_filter = query_filter.format(industry)

    result = industry_docs_collection.find(industry_query_filter, query_projection)

However, it does not work and I get the error:
TypeError: filter must be an instance of dict, bson.son.SON, or other type that inherits from collections.Mapping

So I try to change the filter string into a dict by adding the line:
industry_query_filter = dict(industry_query_filter)
But now I get the error
ValueError: dictionary update sequence element #0 has length 1; 2 is required

I am thinking that this problem must have been solved before by people who use pymongo regularly.

How is this normally handled when multiple queries of a similar form need to be iterated?

1 个答案:

答案 0 :(得分:1)

您本能地使用字典而不是字符串是正确的,但是您编写得不好,应该从头开始构建条件:

cond = {};
cond["sentences"] = {}
cond["sentences"]["$exists"] = True
cond["rank"] = 0
for industry in industry_list:
   cond["industry"] = industry
   result = industry_docs_collection.find(cond, query_projection)