使用mgo驱动程序的Upsert中的$setOnInsert

4
你如何在使用Go MongoDB驱动程序的任何变体上Upsert时使用$setOnInsert
1个回答

6

假设有一个任意类型的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 是一个类型为 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
}

1
对于那些遵循答案但出现“无法同时更新<field>和<field>”错误的人,你在模型中缺少omitempty,或者你可以将"$set": Foo[}更改为"$set": bson.M{} - Lê Quang Bảo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接