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