Golang MongoDB Driver 更新符合条件的数组元素的字段

时间:2022-07-22
本文章向大家介绍Golang MongoDB Driver 更新符合条件的数组元素的字段,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

在 MongoDB 的 Shell 里修改文档里某个符合条件的数组里的值的字段,可以这样:

db.collection.updateMany(
   { <query conditions> },
   { <update operator>: { "<array>.$[<identifier>]" : value } },
   { arrayFilters: [ { <identifier>: <condition> } ] }
)

而在 GoLang 中我们需要使用 MongoDB Driver。

比如有一个 Collection 里每个文档是这样的:

{
      "name": "..",
      "array": []{
            {
                  "name": "a",
                  "detail": "....",
            },
            {
                  "name": "b",
                  "detail": "....",
            }
      }
}

我们要修改 name 为 x 的文档里面 array 里 name 为 b 的记录的 detail 信息为"test"。可以这样写:

filter := bson.M{"name": "x", "array.name": "b"}
update := bson.M{"array.$[item].detail": "test"}
arrayFilter := bson.M{"item.name": "b"}

// coll 是 mongo 的 Collection,下面内容不需要修改。
res := coll.FindOneAndUpdate(context.Background(), 
      filter, 
      bson.M{"$set": update}, 
      options.FindOneAndUpdate().SetArrayFilters(
            options.ArrayFilters{
                  Filters: []interface{}{
                        arrayFilter,
                  },
            },
      ))

if res.Err() != nil {
      // log error      
}