【问题标题】:Querying a nested document in PyMongo在 PyMongo 中查询嵌套文档
【发布时间】: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'}]}]}

提前致谢!

【问题讨论】:

    标签: python mongodb pymongo


    【解决方案1】:

    由于prizes 是一个列表,您可以通过索引访问它的元素。

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

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

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

    【讨论】:

    • 不客气。您可以将答案标记为已接受以“关闭”问题
    猜你喜欢
    • 2018-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-12
    • 1970-01-01
    • 1970-01-01
    • 2022-07-04
    • 2021-02-25
    相关资源
    最近更新 更多