在 PyMongo 中查询嵌套文档

Querying a nested document in PyMongo

我想打印这个名为 NobelDB 的数据库中所有条目的所有名字和获奖年份的列表,集合名称,获奖者。

我可以在 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'])

我如何修改代码以便打印所有名字,以及他们获奖的年份,这些位于 'prizes' 文档中。

数据收集在 'prizes' 处拆分为两个嵌套文档,然后在 'affiliations' 处再次拆分,如下所示:

{'_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'}]}]}

提前致谢!

由于 prizes 是一个列表,您可以使用索引访问其元素。

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

如果你想打印所有年份,你将不得不做另一个循环

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