Creating your first document in MongoDB
In this recipe, we will learn how we can create a BSON document (a binary-encoded serialization of JSON-like documents) in a database, using a MongoDB driver for Go (gopkg.in/mgo.v2).
How to do it…
- Install the
gopkg.in/mgo.v2
andgithub.com/gorilla/mux
packages, using thego get
command, as follows:
$ go get gopkg.in/mgo.v2 $ go get github.com/gorilla/mux
- Create
create-record-mongodb.go
. Then we connect to the MongoDB database, create an employee document with two fields—ID and name—and write the last created document ID to an HTTP response stream, as follows:
package main import ( "fmt" "log" "net/http" "strconv" "github.com/gorilla/mux" mgo "gopkg.in/mgo.v2" ) 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 `json:"name"` } func init() { session, connectionError = mgo.Dial(MONGO_DB_URL) ...