Integrating MongoDB and Go
Whenever you want to persist data in a MongoDB database, the first step you have to take is to establish a connection between the database and your web application, which we will be covering in this recipe using one of the most famous and commonly used MongoDB drivers for Go - gopkg.in/mgo.v2
.
Getting ready…
Verify whether MongoDB
is installed and running locally on port 27017
by executing the following command:
$ mongo
This should return the following response:

How to do it…
- Install the
gopkg.in/mgo.v
package, using thego get
command, as follows:
$ go get gopkg.in/mgo.v
- Create
connect-mongodb.go
. Then we connect to theMongoDB
database, get all the database names from the cluster, and write them to an HTTP response stream, as follows:
package main import ( "fmt" "log" "net/http" "strings" 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 func init...