【发布时间】:2021-06-16 18:22:32
【问题描述】:
我想打印所有名字的列表,以及这个名为 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”处分为两个嵌套文档,然后在“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'}]}]}
提前致谢!
【问题讨论】: