为了账号安全,请及时绑定邮箱和手机立即绑定

Mongodb更新深层嵌套的子文档

Mongodb更新深层嵌套的子文档

蝴蝶不菲 2019-09-21 13:57:56
我有一个深层嵌套的文档结构,如下所示:{id: 1,  forecasts: [ {              forecast_id: 123,              name: "Forecast 1",              levels: [                 { level: "proven",                   configs: [                            {                               config: "Custom 1",                              variables: [{ x: 1, y:2, z:3}]                            },                             {                               config: "Custom 2",                              variables: [{ x: 10, y:20, z:30}]                            },                     ]                },                 { level: "likely",                   configs: [                            {                               config: "Custom 1",                              variables: [{ x: 1, y:2, z:3}]                            },                             {                               config: "Custom 2",                              variables: [{ x: 10, y:20, z:30}]                            },                     ]                }            ]        },     ]}我正在尝试更新集合以插入新的配置,如下所示:newdata =  {  config: "Custom 1",   variables: [{ x: 111, y:2222, z:3333}]}我正在mongo中尝试这样的事情(在Python中):db.myCollection.update({"id": 1,                         "forecasts.forecast-id": 123,                         "forecasts.levels.level": "proven",                         "forecasts.levels.configs.config": "Custom 1"                         },                         {"$set": {"forecasts.$.levels.$.configs.$": newData}}                      )我收到“无法在没有包含数组的相应查询字段的情况下应用位置运算符”错误。在mongo中执行此操作的正确方法是什么?这是mongo v2.4.1。
查看完整描述

3 回答

?
温温酱

TA贡献1752条经验 获得超4个赞

不幸的是,$每个键不能多次使用运算符,因此其余部分必须使用数字值。如:


db.myCollection.update({

    "id": 1, 

    "forecasts.forecast-id": 123, 

    "forecasts.levels.level": "proven", 

    "forecasts.levels.configs.config": "Custom 1"

  },

  {"$set": {"forecasts.$.levels.0.configs.0": newData}}

)

MongoDB对更新嵌套数组的支持很差。因此,如果您需要经常更新数据,则最好避免使用它们,并考虑改用多个集合。


一种可能:创建forecasts自己的集合,并假设您具有一组固定的level值,则创建level一个对象而不是一个数组:


{

  _id: 123,

  parentId: 1,

  name: "Forecast 1", 

  levels: {

    proven: { 

      configs: [

        { 

          config: "Custom 1",

          variables: [{ x: 1, y:2, z:3}]

        }, 

        { 

          config: "Custom 2",

          variables: [{ x: 10, y:20, z:30}]

        }, 

      ]

    },

    likely: {

      configs: [

        { 

          config: "Custom 1",

          variables: [{ x: 1, y:2, z:3}]

        }, 

        { 

          config: "Custom 2",

          variables: [{ x: 10, y:20, z:30}]

        }, 

      ]

    }

  }

}

然后,您可以使用以下命令进行更新:


db.myCollection.update({

    _id: 123,

    'levels.proven.configs.config': 'Custom 1'

  },

  { $set: { 'levels.proven.configs.$': newData }}

)


查看完整回答
反对 回复 2019-09-21
  • 3 回答
  • 0 关注
  • 1978 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信