$addToSet
is an update operation, if you want to update a single document, you may use the Collection.UpdateOne()
method.
Use the bson.M
and/or bson.D
types to describe your filters and update document.
For example:
update := bson.M{
"$addToSet": bson.M{
"tags": bson.M{"$each": []string{"camera", "electronics", "accessories"}},
},
}
res, err := c.UpdateOne(ctx, bson.M{"_id": 2}, update)
Here's a complete, runnable app that connects to a MongoDB server and performs the above update operation:
ctx := context.Background()
client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost"))
if err != nil {
panic(err)
}
defer client.Disconnect(ctx)
c := client.Database("dbname").Collection("inventory")
update := bson.M{
"$addToSet": bson.M{
"tags": bson.M{"$each": []string{"camera", "electronics", "accessories"}},
},
}
res, err := c.UpdateOne(ctx, bson.M{"_id": 2}, update)
if err != nil {
panic(err)
}
fmt.Printf("%+v", res)