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:
JavaScript
x
10
10
1
maDict = {'k1': 'v1', 'k2': 'v2'} # If matches to these field values
2
gtDict = {'k3': 'v3', 'k4': 'v4', 'k5': 'v5'} # and greater than these field values
3
ltDict = {'k6': 'v6'} # and less than these field values
4
diDict = {'k7': 'v7', 'k8': 'v8'} # Then display only these field data 'k7' and 'k8'
5
6
query = {"$and":[{'k1': 'v1'},{'k2': 'v2'},{'k3':{'$gt':'v3'}},{'k4':{'$gt':'v4'}},{'k5':{'$gt':'v5'}},{'k6':{'$lt':'v6'}} ]}
7
8
for x in db[collName].find(query,{'_id': 0, 'k7': 1, 'k8' : 1}):
9
print(x)
10
I could think of converting each dictionary to construct the query string. Is there any better or shortcut method available to achieve
JavaScript
1
6
1
>>> d = {'k3': 'v3'}
2
>>> q = {list(d.keys())[0]:{"$gt": list(d.values())[0]}}
3
>>> q
4
{'k3': {'$gt': 'v3'}}
5
>>>
6
Advertisement
Answer
Thats how you can create your query:
JavaScript
1
14
14
1
query_match = [{k: v} for k, v in maDict.items()]
2
query_gt = [{k: {'$gt': v}} for k, v in gtDict.items()]
3
query_lt = [{k: {'$lt': v}} for k, v in ltDict.items()]
4
query = {"$and": query_match + query_gt + query_lt}
5
print(query)
6
# {'$and': [{'k1': 'v1'}, {'k2': 'v2'}, {'k3': {'$gt': 'v3'}}, {'k4': {'$gt': 'v4'}}, {'k5': {'$gt': 'v5'}}, {'k6': {'$lt': 'v6'}}]}
7
8
fields = {k: 1 for k in diDict.keys()}
9
print(fields)
10
# {'k7': 1, 'k8': 1}
11
12
for x in db[collName].find(query, fields):
13
print(x)
14