在 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
}