使用 mgo.v2 将新对象插入 mongodb 文档中的数组属性

Insert new object into Array Attribute in document in mongodb using mgo.v2

我正在使用 mgo.v2 mongodb 驱动程序来操纵数据 mongodb.I 数据结构如下 json

  "configs": [
        {
          "configid":1,
          "id": 0,
          "widgets": [
            {
              "position": 1,
              "type": 1,
              "class": "normal green",
              "metricid": 5
            },
            {
              "position": 2,
              "type": 1,
              "class": "normal blue",
              "metricid": 6
            }
         ]
      }
    ]

我使用上面的 json 结构创建了 configs 集合。

err2 := session.DB("db").C("configs").Insert(&config)

but.In 我的情况是,我想将新项目添加到 widgets 数组到这个 configid。它是这样的对象,

    {
      "position": 3,
      "type": 1,
      "class": "normal red",
      "metricid": 7
    }

将此对象添加到 mongodb 中特定 configid 的 widgets 数组的最佳方法是什么?我正在使用 mgo.v2 mongodb 驱动程序

您可以使用更新方法使用 $push 运算符添加数组元素。例如:

session.DB("db").C("configs").Update(
    bson.M{"configid": 1}, 
    bson.M{"$push": bson.M{"widgets": widget}}
)