我的MongoDB文档看起来像这样(为清晰起见,删除了不重要的数据):
{
"posts": [
{
"id": 1234,
"comments": "I want this data!"
},
{
"id": 4444,
"comments" "foo"
}
]
}
只知道它在id = 1234的对象中,如何使用Pymongo(Python 3)返回“注释”值,即“我想要这个数据!”?
由于
答案 0 :(得分:0)
遍历dicts列表,找到id == 1234
然后获取comment
值的词组:
dic={
"posts": [
{
"id": 1234,
"comments": "I want this data!",
},
{
"id": 4444,
"comments": "foo",
},
],
}
for d in dic["posts"]:
if d.get("id") == 1234:
print (d.get("comments"))
I want this data!
列表comp:
dic={
"posts": [
{
"id": 1234,
"comments": "I want this data!",
},
{
"id": 4444,
"comments": "foo",
},
{
"id": 1234,
"comments": "I want this data too!",
},
],
}
print ([d.get("comments") for d in dic["posts"] if d.get("id") == 1234])
['I want this data!', 'I want this data too!']