首页 > 解决方案 > 在带有 mgo 驱动程序的 Upsert 上使用 $setOnInsert

问题描述

您如何使用Go MongoDB 驱动程序的$setOnInsert任何Upsert变体?mgo

标签: mongodbgoupsertmgo

解决方案


给定任意类型Foo

type Foo struct {
    ID       bson.ObjectId `json:"_id,omitempty" bson:"_id,omitempty"`
    Bar      string        `json:"bar" bson:"bar"`
    Created  *time.Time    `json:"created,omitempty" bson:"created,omitempty"`
    Modified *time.Time    `json:"modified,omitempty" bson:"modified,omitempty"`
}

还有Upsert选择器,它决定了这是一个Update还是一个Insert

selector := bson.M{
    "bar": "bar",
}

仅当正在插入文档时才插入创建日期的Upsert查询将如下所示(其中now是 type 的变量time.Time):

query := bson.M{
    "$setOnInsert": bson.M{
        "created": &now,
    },
    "$set": Foo{
        Bar:      "bar",
        Modified: &now,
    },
}

将所有这些定义的类型和变量与globalsign/mgo驱动程序一起使用,整个查询由以下代码执行:

if _, err := session.DB("test").C("test").Upsert(selector, query); err != nil {
    // Handle error
}

推荐阅读