1 回答

TA貢獻1780條經(jīng)驗 獲得超5個贊
$addToSet
是一個更新操作,如果你想更新單個文檔,可以使用該Collection.UpdateOne()
方法。
使用bson.M
和/或bson.D
類型來描述您的過濾器和更新文檔。
例如:
update := bson.M{
? ? "$addToSet": bson.M{
? ? ? ? "tags": bson.M{"$each": []string{"camera", "electronics", "accessories"}},
? ? },
}
res, err := c.UpdateOne(ctx, bson.M{"_id": 2}, update)
這是一個完整的、可運行的應(yīng)用程序,它連接到 MongoDB 服務(wù)器并執(zhí)行上述更新操作:
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)
- 1 回答
- 0 關(guān)注
- 128 瀏覽
添加回答
舉報