在PyMongo中查询嵌套文档

2024-09-30 22:14:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我想打印一份所有名字的列表,以及得奖那一年数据库中所有名为NobelDB,收藏名,laureate的条目

我可以用PyMongo中的以下代码打印名字:

Q = laureate.find({})
for q in Q:
    print(q['firstname'])

但是,当我像下面那样将嵌套查询添加到for循环中时,它会打印一个错误:

Q = laureate.find({})
for q in Q:
print(q['firstname'],
     q['prizes.year'])

我如何修改代码,使其打印出所有的名字,以及他们获奖的年份(位于“奖品”文档中)

数据收集分为两个嵌套文档,分别位于“奖品”和“附属机构”,如下所示:

{'_id': ObjectId('60534c9fe877bf1b14149668'), 'id': '2', 'firstname': 'Hendrik A.', 'surname': 'Lorentz', 'born': '1853-07-18', 'died': '1928-02-04', 'bornCountry': 'the Netherlands', 'bornCountryCode': 'NL', 'bornCity': 'Arnhem', 'diedCountry': 'the Netherlands', 'diedCountryCode': 'NL', 'gender': 'male', 
'prizes': [{'year': '1902', 'category': 'physics', 'share': '2', 'motivation': '"in recognition of the extraordinary service they rendered by their researches into the influence of magnetism upon radiation phenomena"', 
'affiliations': [{'name': 'Leiden University', 'city': 'Leiden', 'country': 'the Netherlands'}]}]}

提前谢谢


Tags: the代码in文档idforfindfirstname
1条回答
网友
1楼 · 发布于 2024-09-30 22:14:51

因为prizes是一个列表,所以可以使用索引访问它的元素

q["prizes"][0]["year"]

如果你想把这些年都打印出来,你必须做另一个循环

for q in Q:
    print(q['firstname'])
    for prize in q["prizes"]
        print(prize["year")

相关问题 更多 >