Updating your first document in MongoDB
Once a BSON document is created we may need to update some of its fields. In that case, we have to execute update/upsert
queries on the MongoDB collection, which we will be covering in this recipe.
How to do it…
- Install the
gopkg.in/mgo.v2
,gopkg.in/mgo.v2/bson
, andgithub.com/gorilla/mux
packages, using thego get
command, as follows:
$ go get gopkg.in/mgo.v2 $ go get gopkg.in/mgo.v2/bson $ go get github.com/gorilla/mux
- Create
update-record-mongodb.go
. Then we connect to the MongoDB database, update the name of an employee for an ID, and write the number of records updated in MongoDB to an HTTP response stream, as follows:
package main import ( "fmt" "log" "net/http" "strconv" "github.com/gorilla/mux" mgo "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" ) const ( CONN_HOST = "localhost" CONN_PORT = "8080" MONGO_DB_URL = "127.0.0.1" ) var session *mgo.Session var connectionError error type Employee struct { Id int `json:"uid"` Name string...