Deleting your first document from MongoDB
Whenever we want to clean up the database or delete the documents that are no longer needed, we can easily remove them using a MongoDB driver for Go (gopkg.in/mgo.v2), 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
delete-record-mongodb.go
. Then we connect to MongoDB, get the name of an employee to be deleted from the database as an HTTP request variable, get the named collection, and remove the document, as follows:
package main import ( "fmt" "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 type Employee struct { Id int `json:"uid"` ...