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

Raf*_*erg 9 go mongodb

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

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"`
}
Run Code Online (Sandbox Code Playgroud)

我收到了一个包含多个 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)
    }

}
Run Code Online (Sandbox Code Playgroud)

但是现在Upsert它不起作用。当我将手动文档放入 MongoDB 并运行该程序时,它正在更新。那么为什么没有在数据库中创建新实例呢?我必须在某处upsert=True或某处声明吗?或者可能是"orderItems": OpenOrderCleaned.OrderItems不正确的映射?

任何帮助表示赞赏。

Bur*_*dar 19

您正在调用更新,而不是 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)
Run Code Online (Sandbox Code Playgroud)

你错过了opts.