Instagram
youtube
Facebook
Twitter

How to Connect Mongo DB with Golang

What is Mongo DB?

MongoDB is a NoSQL database that is open source. It is a document-oriented database that stores documents in a JSON-like structure called BSON (i.e. key-value pairs). MongoDB uses the concept of collection to organize documents. 

Get the Mongo DB package for golang

This package provides the Mongo DB driver API which is used to interact with the Mongo DB server. you can use the command follow:

go get go.mongodb.org/mongo-driver/mongo

Connecting to the Mongo DB server

Now, We are going to use the following points in order to establish a successful connection to the Mongo DB server.

  • Using the mongo.Connect function, create a mongo.Client. The connection to MongoDB is handled by the mongo. Client.
  • mongo.
  • On a successful connection, the client's Ping method returns pong.
  • Finally, use the mongo.client 
  • so, disconnect from the database, press the Disconnect button
package main

import (
	"context"
	"fmt"
	"time"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"go.mongodb.org/mongo-driver/mongo/readpref"
)

func close(client *mongo.Client, ctx context.Context,
		cancel context.CancelFunc){
			
	// CancelFunc to cancel to context
	defer cancel()
	
	defer func(){
	
		// checking errors,
		if err := client.Disconnect(ctx); err != nil{
			panic(err)
		}
	}()
}

func connect(uri string)(*mongo.Client, context.Context,
						context.CancelFunc, error) {
						
	ctx, cancel := context.WithTimeout(context.Background(),
									30 * time.Second)
	
	// mongo.Connect return mongo.Client method
	client, err := mongo.Connect(ctx, options.Client().ApplyURI(uri))
	return client, ctx, cancel, err
}

func ping(client *mongo.Client, ctx context.Context) error{

	// mongo.Client has Ping to ping mongoDB, deadline of
	// Ping method return error if any occurred, then
	// the error can be handled.
	if err := client.Ping(ctx, readpref.Primary()); err != nil {
		return err
	}
	fmt.Println("connected successfully")
	return nil
}

func main(){

	client, ctx, cancel, err := connect("mongodb://localhost:27017")
	if err != nil
	{
		panic(err)
	}
	
	
	defer close(client, ctx, cancel)
	
	ping(client, ctx)
}

By running this code it will display "connected successfully".