cryanbhu
cryanbhu

Reputation: 5264

How to iterate multiple Pymongo query filters with different values

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?

Upvotes: 1

Views: 165

Answers (1)

Tom Slabbaert
Tom Slabbaert

Reputation: 22316

You're instinct on using a dict instead of a string is right, however you didn't write it well, you should build the condition from scratch:

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)

Upvotes: 1

Related Questions