如果我有這樣的json:
query = {
"canonical.operatingSystemFamily": "Linux",
"canonical.region": "us-east-1"
}
我可以將它直接傳遞給 find 并且它可以作業:
self._db_conn[collection_name].find(query)
我也想做同樣的事情,但是使用串列,例如:
query = {
"canonical.operatingSystemFamily": ["Linux","Windows"],
"canonical.region": ["us-east-1", "us-east-2"]
}
有沒有辦法做到這一點?我知道“$in”,但我不想決議我的查詢資料。這是一個非常簡化的示例,有很多欄位可能存在也可能不存在。有沒有辦法直接使用帶有串列的json?
uj5u.com熱心網友回復:
它不是一個決議器——只是檢查type.
$ ipython
Python 3.8.10 (default, May 4 2021, 00:00:00)
Type 'copyright', 'credits' or 'license' for more information
IPython 8.1.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: query = {
...: "canonical.operatingSystemFamily": ["Linux","Windows"],
...: "canonical.region": ["us-east-1", "us-east-2"]
...: }
In [2]: for k,v in query.items():
...: if type(v)==list:
...: query[k]={"$in": v}
...:
In [3]: query
Out[3]:
{'canonical.operatingSystemFamily': {'$in': ['Linux', 'Windows']},
'canonical.region': {'$in': ['us-east-1', 'us-east-2']}}
如果您愿意,您可以定義一個函式以query在 alist存在時進行轉換。
from copy import deepcopy
def query_lfixer(query, copy=True):
if copy:
query = deepcopy(query)
for k, v in query.items():
if type(v)==list:
query[k] = {"$in": v}
return query
然后你可以像這樣使用它:
self._db_conn[collection_name].find(query_lfixer(query))
或者你也可以通過query任何其他方式進行轉換。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/437030.html
