亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將 UpdateOne 與 MongoDB Golang 驅動程序一起使用時,更新插入不起作用

將 UpdateOne 與 MongoDB Golang 驅動程序一起使用時,更新插入不起作用

Go
白豬掌柜的 2023-08-14 15:00:29
作為參考,我有這個結構:type OpenOrderCleaned struct {    OrderID             string    `json:"orderId" bson:"orderId"`    DateTimeOrderPlaced time.Time `json:"dateTimeOrderPlaced" bson:"dateTimeOrderPlaced"`    OrderItems          []struct {        OrderItemID   string `json:"orderItemId" bson:"orderItemId"`        Ean           string `json:"ean" bson:"ean"`        CancelRequest bool   `json:"cancelRequest" bson:"cancelRequest"`        Quantity      int    `json:"quantity" bson:"quantity"`    } `json:"orderItems" bson:"orderItems"`}我收到一個包含多個 JSON 實例的 API 響應,我想將這些實例保存在 MongoDB 中,因此我使用了 for 循環。我想通過使用該字段來檢查數據庫中是否已存在文檔,orderId該字段對于每個 JSON 實例都是唯一的。我認為UpdateOne這是一個不錯的選擇,因為它有upsert. 因此,如果 orderId 不存在,則應生成完整文檔并將其存儲在數據庫中。for _, OpenOrderCleaned := range o.Orders {    c := auth.GetClient()    collection := c.Database("goprac").Collection(x)    filter := bson.M{"orderId": bson.M{"$eq": OpenOrderCleaned.OrderID}}    update := bson.M{        "$set": bson.M{            "orderId":             OpenOrderCleaned.OrderID,            "dateTimeOrderPlaced": OpenOrderCleaned.DateTimeOrderPlaced,            "orderItems":          OpenOrderCleaned.OrderItems,        },    }    ctx, _ := context.WithTimeout(context.Background(), 15*time.Second)    result, err := collection.UpdateOne(ctx, filter, update)    if err != nil {        fmt.Println("UpdateOne() result ERROR:", err)        os.Exit(1)    } else {        fmt.Println("UpdateOne() result:", result)        fmt.Println("UpdateOne() result TYPE:", reflect.TypeOf(result))        fmt.Println("UpdateOne() result MatchedCount:", result.MatchedCount)        fmt.Println("UpdateOne() result ModifiedCount:", result.ModifiedCount)        fmt.Println("UpdateOne() result UpsertedCount:", result.UpsertedCount)        fmt.Println("UpdateOne() result UpsertedID:", result.UpsertedID)    }}但現在Upsert不起作用。當我將手動文檔放入 MongoDB 并運行該程序時,它正在更新。那么為什么數據庫中沒有創建新實例呢?我必須在某處upsert=True或某事上聲明嗎?或者也許映射"orderItems":          OpenOrderCleaned.OrderItems不正確?任何幫助表示贊賞。
查看完整描述

1 回答

?
ITMISS

TA貢獻1871條經驗 獲得超8個贊

您正在調用更新,而不是更新插入。您必須傳遞正確的選項才能UpdateOne進行更新插入。這是來自 mongo 驅動程序示例:


opts := options.Update().SetUpsert(true)

filter := bson.D{{"_id", id}}

update := bson.D{{"$set", bson.D{{"email", "[email protected]"}}}}


result, err := coll.UpdateOne(context.TODO(), filter, update, opts)

您缺少opts.


查看完整回答
反對 回復 2023-08-14
  • 1 回答
  • 0 關注
  • 222 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號