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.
Reading documents from MongoDB
How to do it...
- Install the gopkg.in/mgo.v2, gopkg.in/mgo.v2/bson, and github.com/gorilla/mux packages, using the go get command, 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"
"...