[英]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”处分为两个嵌套文档,然后在“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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.