示例文檔{"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)
}
- 1 回答
- 0 關注
- 120 瀏覽
添加回答
舉報
0/150
提交
取消