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.