【问题标题】:Python MongoDB: How to add a nested dictionary to a key in an existing DocumentPython MongoDB:如何将嵌套字典添加到现有文档中的键
【发布时间】:2022-01-21 07:54:19
【问题描述】:

我使用 Python 已经有一段时间了,现在想学习 DB。我正在努力学习 MongoDB。

目标:将嵌套字典添加到预先存在的文档中的键。

我为此使用 Pymongo。

例如。我有这个-

{'name':'Ryan', 'titles':[{'title_name':'Victory Set'}]}

我想在titles键中添加另一个字典,让它看起来像这样-

{'name':'Ryan', 'titles':[{'title_name':'Victory Set'}, {'title_name':'Bronze Trial'}]}

我看到您可以使用update_oneupdate_many 更新预先存在的值,但找不到添加新数据。 我怎样才能做到这一点?

【问题讨论】:

    标签: python mongodb dictionary nested pymongo


    【解决方案1】:

    试试这个,参考https://mongoplayground.net/p/P5w6bF0UtWj

    db.collection.update({
      "name": "Ryan"
    },
    {
      "$push": {
        "titles": {
          "$each": [
            {
              "title_name": "Bronze Trial"
            },
            {
              "title_name": "Silver Trial"
            }
          ],
          
        }
      }
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-11
      • 2013-09-19
      • 2018-04-25
      • 1970-01-01
      • 1970-01-01
      • 2020-04-12
      • 2018-11-07
      • 1970-01-01
      相关资源
      最近更新 更多