Tim
Tim

Reputation: 99428

How to do partial and full updates on a document using mgo in Go

From Web Development with Go by Shiju Varghese, about the update method in the MongoDB driver mgo in Go

Updating Documents

The Update method of the Collection type allows you to update existing documents. Here is the method signature of the Update method:

func (c *Collection) Update(selector interface{}, update interface{}) error

The Update method finds a single document from the collection, matches it with the provided selector document, and modifies it based on the provided update document. A partial update can be done by using the keyword "$set" in the update document.

Listing 8-14 updates an existing document.

err := c.Update(bson.M{"_id": id},
bson.M{"$set": bson.M{
"description": "Create open-source projects",
"tasks": []Task{
Task{" Evaluate Negroni Project", time.Date(2015, time.August, 15, 0, 0, 0, 
0, time.UTC)},
Task{" Explore mgo Project", time.Date(2015, time.August, 10, 0, 0, 0, 0, 
time.UTC)},
Task{" Explore Gorilla Toolkit", time.Date(2015, time.August, 10, 0, 0, 0, 0, 
time.UTC)},
},
}})

A partial update is performed for the fields’ descriptions and tasks. The Update method finds the document with the provided _id value and modifies the fields based on the provided document.

The example is a partial update. It uses two-level nested bson.M to create update interface{}. Does a partial update always use such two-level nested bson.M?

Does a full update use one-level bson.M, such as

err := c.Update(bson.M{"_id": id},
bson.M{ "description": "Create open-source projects",
"tasks": []Task{
Task{" Evaluate Negroni Project", time.Date(2015, time.August, 15, 0, 0, 0, 
0, time.UTC)},
Task{" Explore mgo Project", time.Date(2015, time.August, 10, 0, 0, 0, 0, 
time.UTC)},
Task{" Explore Gorilla Toolkit", time.Date(2015, time.August, 10, 0, 0, 0, 0, 
time.UTC)},
},
})

Thanks.

Upvotes: 1

Views: 3453

Answers (1)

CrazyCrow
CrazyCrow

Reputation: 4235

  1. Yes, the partial update always requires $set. This is not about Go this is about Mongo $set operator bson.M is just the shortcut for map[string]interface{} which allows us to build JSON-like structures in go without thinking about argument type. So, as you always need $set the update document always will have at least two levels of bson.M. Actually, there are more levels as your Task objects could be defined as bson.M objects too.

  2. Yes, the full document update (personally I think this process looks more like replace) requires only 2 bson.M objects - the query and the new document.

    In Mongo full update looks like

    db.collection.update({_id: "id"}, {name: "name", num: 1})

    And the same command in Go:

    c.Update(bson.M{"_id": "id"}, bson.M{"name": "name", "num": 1})

Upvotes: 2

Related Questions