繁体   English   中英

将 UpdateOne 与 MongoDB Golang 驱动程序一起使用时,Upsert 不起作用

[英]Upsert not working when using UpdateOne with the MongoDB Golang driver

作为参考,我有这个结构:

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的映射"orderItems": OpenOrderCleaned.OrderItems不正确?

任何帮助表示赞赏。

您正在调用更新,而不是 upsert。 您必须将正确的选项传递给UpdateOne以进行 upsert。 这是来自 mongo 驱动程序示例:

opts := options.Update().SetUpsert(true)
filter := bson.D{{"_id", id}}
update := bson.D{{"$set", bson.D{{"email", "newemail@example.com"}}}}

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

你错过了opts

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM