使用 $setOnInsert 在 Upsert 上使用 mgo 驱动程序

Geo*_* IV 3 upsert go mongodb mgo

如何使用$setOnInsertUpsert有任何的mgo围棋MongoDB的驱动程序的变种?

Geo*_* IV 5

鉴于任意类型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"`
}
Run Code Online (Sandbox Code Playgroud)

Upsert选择器,它确定这将是 anUpdate还是 an Insert

selector := bson.M{
    "bar": "bar",
}
Run Code Online (Sandbox Code Playgroud)

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

query := bson.M{
    "$setOnInsert": bson.M{
        "created": &now,
    },
    "$set": Foo{
        Bar:      "bar",
        Modified: &now,
    },
}
Run Code Online (Sandbox Code Playgroud)

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

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