3

I need to do addToSet operation using official Go MongoDB driver.

In MongoDB we have some docs:

{ _id: 2, item: "cable", tags: [ "electronics", "supplies" ] }

Then to perform addToSet:

db.inventory.update(
   { _id: 2 },
   { $addToSet: { tags: { $each: [ "camera", "electronics", "accessories" ] } } }
)

Result:

{
  _id: 2,
  item: "cable",
  tags: [ "electronics", "supplies", "camera", "accessories" ]
}
icza
  • 389,944
  • 63
  • 907
  • 827
Bijak Antusias Sufi
  • 198
  • 2
  • 5
  • 18

1 Answers1

5

$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)
icza
  • 389,944
  • 63
  • 907
  • 827
  • What to do when I'm not sure which field user wants to update? e.g let's imagine this is out model `id: 123, name: Varun, pwd : qwerty`. A user wants to update their name then we'll do what's defined in the answer. But imagine next time a user wants to update their password then what we will do? – OhhhThatVarun Sep 19 '19 at 20:43