0% found this document useful (0 votes)
67 views

Go & Mongo: Install Mongodb Driver

This document provides instructions for connecting to a MongoDB Atlas cluster from a Go application. It describes initializing Go modules, installing the MongoDB driver, getting the connection string from MongoDB Atlas, and includes code to connect to the cluster, check the connection, list databases, and disconnect. The code connects to the cluster, pings it to check the connection, prints available databases, and disconnects when finished.

Uploaded by

Fatima
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
67 views

Go & Mongo: Install Mongodb Driver

This document provides instructions for connecting to a MongoDB Atlas cluster from a Go application. It describes initializing Go modules, installing the MongoDB driver, getting the connection string from MongoDB Atlas, and includes code to connect to the cluster, check the connection, list databases, and disconnect. The code connects to the cluster, pings it to check the connection, prints available databases, and disconnects when finished.

Uploaded by

Fatima
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Go & Mongo

In this project I am going to use Mongo Atlas Cluster.

Checkout this quick walkthrough and create your first free cluster. 

Install MongoDB Driver


We will use go modules to manage all the packages. So, fire up your bash and get started

● Initialize Go modules

go mod init LiveShoppingCart 

● Install mongo driver

go get go.mongodb.org/mongo-driver 

Connecting Via Mongo Driver


Getting connection String

● Go to your cluster Page


● pick your cluster
● click to connect & add ip adress 

Though you can allow access from any IP but it’s safe to
whitelist your IP so that anyone cannot access your
connection. check this page to know more.

● Choose connection method


● Create a database
○ Go to connection tab into your cluster
○ Add new Database
○ Now you can add collections in your database
● Select the following connection method

● Select Driver and version 


● Copy the connection String and edit db user password and database name

So Now we have everything ready in MongoDB Atlas. Now it’s time to jump into coding.

Create ConnectToAtlas.go file and add the followings

Add the following Packages. Please checkout the package details from this page

import (
    "context"
    "fmt"
    "log"
    "time"
    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
    "go.mongodb.org/mongo-driver/mongo/readpref"
)

Add ConnectToAtlas() function which is responsible to

● Connect to the Mongo Atlas cluster


● Check if the server is connected
● Check available database
● Disconnect from Mongo Atlas

func ConnectToAtlas(){
    client, err := mongo.NewClient(options.Client().ApplyURI("the connection string yo
    if err != nil {
        log.Fatal(err)
    }

    // Adding a timeout for the connection request


    ctx, _ := context.WithTimeout(context.Background(), 15*time.Second)
    err = client.Connect(ctx)
    if err != nil {
        log.Fatal(err)
    }

    // Ping the cluster to check if the client is connected


    err = client.Ping(ctx, readpref.Primary())
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("Connected to the server ^_^ ")

    //check the databases


    databases, err := client.ListDatabaseNames(ctx, bson.M{})
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("Checkout available Databases")
    fmt.Println(databases)
    fmt.Println("Disconnecting...")
    defer client.Disconnect(ctx)
    fmt.Println("disconnected!")
}

Create a main.go file and call the ConnectToAtlas()

package main
import (    
    "fmt"
)
func main(){
    fmt.Println("connecting to the server....")
    ConnectToAtlas()
}

run the following commands in your terminal

go build // it will create a executable file


executatableFileName.exe

You should see the following result

You might also like