问题
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