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