Search code examples
mongodbgomongo-go

How can update multiple documents using multiple targets


example documents

{"id": 1, "alive":true},
{"id": 2, "alive":true},
{"id": 3, "alive":true},
{"id": 4, "alive":true}

problem

if got targets like var targetIds []int{1, 3, 4}. Want to update multiple documents's alive value to 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

UPDATE [my_table] SET alive = false WHERE id IN [targetIds];

not using for loop. one query like the way in example postgresql query

is there similar way in Go mongodb driver?


Solution

  • Use Collection.UpdateMany() instead of Collection.UpdateOne(), and construct a filter that matches the slice of IDs:

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