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      
}
posted @ 2020-08-04 19:58  水郁  阅读(1499)  评论(0编辑  收藏  举报
……