亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用多個目標更新多個文檔

如何使用多個目標更新多個文檔

Go
LEATH 2022-08-09 20:15:12
示例文檔{"id": 1, "alive":true},{"id": 2, "alive":true},{"id": 3, "alive":true},{"id": 4, "alive":true}問題如果有像.想要將多個文檔的活動值更新為 false。目前使用這種方式。var targetIds []int{1, 3, 4}var targetIds []int{1, 3, 4}collection := MongoClient.Database("my_database").Collection("my_collection")updateDoc := bson.M {    "$set": bson.M {        "alive": false,    }}for _, targetId := range targetIds{    filter := bson.M{        "id": targetId,    }    _, err := collection.UpdateOne(context.Background(), filter, updateDoc)    if err != nil {        panic(err)    }}例如,在postgresql中可以使用這種方式UPDATE [my_table] SET alive = false WHERE id IN [targetIds];不使用 for 循環。一個查詢,就像示例 postgresql 查詢中的方式在Go mongodb驅動程序中是否有類似的方法?
查看完整描述

1 回答

?
慕哥9229398

TA貢獻1877條經驗 獲得超6個贊

使用Collection.UpdateMany()而不是Collection.UpdateOne(),并構造一個與ID切片匹配的過濾器:

filter := bson.M{

    "id": bson.M{"$in": targetIds},

}

_, err := collection.UpdateMany(context.Background(), filter, updateDoc)

if err != nil {

    panic(err)

}


查看完整回答
反對 回復 2022-08-09
  • 1 回答
  • 0 關注
  • 120 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號