`col={"a":{"x":1,"y":2},"b":[{"w":5,"z":7},{"w":8,"z":5}]}`
`col.find({"a.x":1}) or col.find({"b.w":5})`
`data1=[]
data2=[]
finddata={}
for data in col.find({}):
finddata=dict(data)
for key,value in finddata.items():
if key == "a.x": #if key=="a" will works
data1.append(value)
if key == "b.w":
data2.append(value)`
有人可以帮助我吗?谢谢
答案 0 :(得分:0)
使用Mongo聚合管道,可以投影您关心的字段,并将其替换为返回的根文档中的返回字段。 例如
pipeline = [
{'$project': {'a.x':1, 'b.w': 1}},
{'$replaceRoot': {'newRoot': {'a_x': '$a.x', 'b_w': '$b.w'}}}
]
cur = db.keyes.aggregate(pipeline)
result = next(cur)
这样,您可以继续使用结果扩展相应的列表。
tolist = lambda x: x if isinstance(x, list) else [x]
data1.extend(tolist(result['a_x']))
data2.extend(tolist(result['b_w']))
答案 1 :(得分:0)
def get_dict_in(Dict,objkey,default):
for key,value in Dict.items():
if key == objkey:
return value
else:
if type(value) is dict: # Note: import types
val=get_dict_in(value,objkey,default)
if default not in val:
return val
return default
例如
dictA={"a":{"x":1,"y":2},"b":[{"w":5,"z":7},{"w":8,"z":5}]}
value=get_dict_in(dictA,'x',None)