Search code examples
mongodbgomongo-go

How to perform addToSet using Go official driver?


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" ]
}

Solution

  • $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)