![](/img/trans.png)
[英]How to find specific key:value 2 from python pymongo, MongoDB
[英]How pymongo define the key for append the value
`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)`
谁能帮我吗?
使用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']))
dictA={"a":{"x":1,"y":2},"b":[{"w":5,"z":7},{"w":8,"z":5}]}
value=get_dict_in(dictA,'x',None)
例如
dictA={"a":{"x":1,"y":2},"b":[{"w":5,"z":7},{"w":8,"z":5}]} value=get_dict_in(dictA,'x',None)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.