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      
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM