1

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 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

thanks! this works. Also seems like piecing the dictionary together as a Python dict instead of writing it out in one line like a string or in curly brace syntax is a better idea!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.