Reading documents from MongoDB
In the previous recipe, we created a BSON document in MongoDB. Now, in this recipe, we will learn how to read it using the gopkg.in/mgo.v2/bson package, which helps to query the MongoDB collection.
How to do it…
- Install the
gopkg.in/mgo.v2,gopkg.in/mgo.v2/bson, andgithub.com/gorilla/muxpackages, using thego getcommand, as follows:
$ go get gopkg.in/mgo.v2 $ go get gopkg.in/mgo.v2/bson $ go get github.com/gorilla/mux
- Create
read-record-mongodb.go. Then we connect to the MongoDB database, read all the documents from an employee collection, marshal the list to JSON, and write it to an HTTP response stream, as follows:
package main
import
(
"encoding/json"
"log"
"net/http"
"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
func init()
{
session, connectionError = mgo.Dial(MONGO_DB_URL)
if...