[英]How can update multiple documents using multiple targets
{"id": 1, "alive":true},
{"id": 2, "alive":true},
{"id": 3, "alive":true},
{"id": 4, "alive":true}
if got targets like var targetIds []int{1, 3, 4}
.如果得到像var targetIds []int{1, 3, 4}
这样的目标。 Want to update multiple documents's alive value to false.想要将多个文档的 alive 值更新为 false。 Currently using this way.目前采用这种方式。
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)
}
}
for example in postgresql can use this way例如在 postgresql 中可以使用这种方式
UPDATE [my_table] SET alive = false WHERE id IN [targetIds];
not using for loop.不使用 for 循环。 one query like the way in example postgresql query一个查询就像示例 postgresql 查询中的方式
is there similar way in Go mongodb driver? Go mongodb 驱动程序中有类似的方法吗?
Use Collection.UpdateMany()
instead of Collection.UpdateOne()
, and construct a filter that matches the slice of IDs:使用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)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.