How to perform addToSet using Go official driver?

守給你的承諾、 提交于 2021-02-15 07:08:34

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/57586592/how-to-perform-addtoset-using-go-official-driver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!