George Edward Shaw IV
George Edward Shaw IV

Reputation: 835

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?

Upvotes: 4

Views: 1885

Answers (1)

George Edward Shaw IV
George Edward Shaw IV

Reputation: 835

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
}

Upvotes: 6

Related Questions