gpt4 book ai didi

mongodb - 如何使用多个目标更新多个文档

转载 作者:行者123 更新时间:2023-12-03 10:09:06 24 4
gpt4 key购买 nike

示例文件

{"id": 1, "alive":true},
{"id": 2, "alive":true},
{"id": 3, "alive":true},
{"id": 4, "alive":true}
问题
如果有类似 var targetIds []int{1, 3, 4}的目标。想要将多个文档的有效值更新为false。目前正在使用这种方式。
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驱动程序中有类似的方法吗?

最佳答案

使用 Collection.UpdateMany() 而不是 Collection.UpdateOne() ,并构造一个与ID slice 匹配的过滤器:

filter := bson.M{
"id": bson.M{"$in": targetIds},
}
_, err := collection.UpdateMany(context.Background(), filter, updateDoc)
if err != nil {
panic(err)
}

关于mongodb - 如何使用多个目标更新多个文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66238422/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com