Mongo connection with go lang

Ankit Kumar Rajpoot
1 min readAug 14, 2022

In this article, we will discuss how to make the connection with mongodb by single separate file.

Make a single file for the connection’s separate code, path will be db/mongo.go

package dbimport ("go-echo-restful-api/config"
"github.com/labstack/gommon/log"
mgo "gopkg.in/mgo.v2"
)
var (
session *mgo.Session
databaseName = "example"
)
func init() {
stgConnection()
}
func stgConnection() {
hosts := config.Config.Database.Address // localhost
mgoSession, err := mgo.Dial(hosts)
if err != nil {
log.Fatal(err)
}
session = mgoSession
}
func pullSession() *mgo.Session {
return session.Copy()
}
// Ping connection
func Ping() error {
sessionCopy := pullSession()
defer sessionCopy.Close()
return sessionCopy.Ping()
}

How will be call from main file.

err := db.Ping()
if err != nil {
logrus.Fatal(err)
}

That’s it for this time! I hope you enjoyed this post. As always, I welcome questions, notes, comments and requests for posts on topics you’d like to read. See you next time! Happy Coding !!!!!

--

--

Ankit Kumar Rajpoot

I’m a MERN Developer. ( Redux | AWS | Python ) I enjoy taking on new things, building skills, and sharing what I’ve learned.