如何使用多个目标更新多个文档
How can update multiple documents using multiple targets
示例文档
{"id": 1, "alive":true},
{"id": 2, "alive":true},
{"id": 3, "alive":true},
{"id": 4, "alive":true}
问题
如果有 var targetIds []int{1, 3, 4}
这样的目标。想要将多个文档的 alive 值更新为 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 查询中的方式
Gomongodb驱动有类似的方法吗?
使用 Collection.UpdateMany()
instead of Collection.UpdateOne()
,并构造一个匹配 ID 切片的过滤器:
filter := bson.M{
"id": bson.M{"$in": targetIds},
}
_, err := collection.UpdateMany(context.Background(), filter, updateDoc)
if err != nil {
panic(err)
}
示例文档
{"id": 1, "alive":true},
{"id": 2, "alive":true},
{"id": 3, "alive":true},
{"id": 4, "alive":true}
问题
如果有 var targetIds []int{1, 3, 4}
这样的目标。想要将多个文档的 alive 值更新为 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 查询中的方式
Gomongodb驱动有类似的方法吗?
使用 Collection.UpdateMany()
instead of Collection.UpdateOne()
,并构造一个匹配 ID 切片的过滤器:
filter := bson.M{
"id": bson.M{"$in": targetIds},
}
_, err := collection.UpdateMany(context.Background(), filter, updateDoc)
if err != nil {
panic(err)
}