Skip to content
Advertisement

How to construct pymongo query string from dictionary

My MongoDB documents looks like {'k1': 'v1', 'k2': 'v2', 'k3': 'v3' . . .}

Would like to construct a pymongo query string where Keys and Values in maDict are Match, gtDict are greater than and ltDict are less than and display only the fields specified in diDict:

maDict = {'k1': 'v1', 'k2': 'v2'}               # If matches to these field values
gtDict = {'k3': 'v3', 'k4': 'v4', 'k5': 'v5'}   # and greater than these field values 
ltDict = {'k6': 'v6'}                           # and less than these field values
diDict = {'k7': 'v7', 'k8': 'v8'}               # Then display only these field data 'k7' and 'k8'

query = {"$and":[{'k1': 'v1'},{'k2': 'v2'},{'k3':{'$gt':'v3'}},{'k4':{'$gt':'v4'}},{'k5':{'$gt':'v5'}},{'k6':{'$lt':'v6'}} ]}
                                  
for x in db[collName].find(query,{'_id': 0, 'k7': 1, 'k8' : 1}):
  print(x)

I could think of converting each dictionary to construct the query string. Is there any better or shortcut method available to achieve

>>> d = {'k3': 'v3'}
>>> q = {list(d.keys())[0]:{"$gt": list(d.values())[0]}}
>>> q
{'k3': {'$gt': 'v3'}}
>>>

Advertisement

Answer

Thats how you can create your query:

query_match = [{k: v} for k, v in maDict.items()]
query_gt = [{k: {'$gt': v}} for k, v in gtDict.items()]
query_lt = [{k: {'$lt': v}} for k, v in ltDict.items()]
query = {"$and": query_match + query_gt + query_lt}
print(query)
# {'$and': [{'k1': 'v1'}, {'k2': 'v2'}, {'k3': {'$gt': 'v3'}}, {'k4': {'$gt': 'v4'}}, {'k5': {'$gt': 'v5'}}, {'k6': {'$lt': 'v6'}}]}

fields = {k: 1 for k in diDict.keys()}
print(fields)
# {'k7': 1, 'k8': 1}

for x in db[collName].find(query, fields):
  print(x)
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement