Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using $setOnInsert on Upsert With mgo Driver

How do you use $setOnInsert on an Upsert with any of the mgo variants of the Go MongoDB drivers?

like image 473
George Edward Shaw IV Avatar asked Sep 09 '25 14:09

George Edward Shaw IV


1 Answers

Given the arbitrary type 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"`
}

And the Upsert selector, which determines whether or not this will be an Update or an Insert:

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

The Upsert query to insert a created date only if the document is being inserted will look like this (where now is a variable of type time.Time):

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

Using all of these defined types and variables with the globalsign/mgo driver, this entire query is executed by the following code:

if _, err := session.DB("test").C("test").Upsert(selector, query); err != nil {
    // Handle error
}
like image 158
George Edward Shaw IV Avatar answered Sep 12 '25 04:09

George Edward Shaw IV