You are currently viewing How to connect the Golang app with MongoDB Database

How to connect the Golang app with MongoDB Database

Introduction

In this tutorial blog, you are going to learn, how to connect your MongoDB Database to your Golang Application. This tutorial will also give you some basic ideas regarding Golang Packages. Installation of Golang, setting up your workspace, what are dependencies in Golang, and some idea regarding MongoDB Atlas has also been covered in this blog. If you are looking to hire Golang developers or learn golang yourself, you have landed at the right place. Before proceeding, there are some prerequisites that you need to be prepared with. I have mentioned the prerequisites below,

Prerequisites

  • You need to install Golang on your PC, you can download it with the help of this link. After getting into the website of Go, you will notice that there are download options for different OS. You can select a file according to your OS, download it, and install it.
  • You need to open up MongoDB Atlas on your browser and create an account in it. To connect your Golang App to your database. I will be discussing more on MongoDB Atlas in the later parts of my blog.
  • You need an IDE to write your code. For my blog, I am using Visual Studio Code which is very popular among developers nowadays. I suggest going for Visual Studio Itself. 

MongoDB Setup

In this section, I will be giving you an idea regarding MongoDB Atlas, what I will do with it, and how. To begin with, Let’s understand what is MongoDB Atlas. 

MongoDb Atlas is a cloud version of MongoDB which is developed by MongoDB Developers itself. I will use MongoDB because of its elevated availability and scalability abilities. It is becoming popular nowadays among developers and widely used product developed by Mongo Team. 

Hereafter creating the account in MongoDB Atlas, I will fetch the URI String from it, which I will copy down in code for establishing a connection with my database. After fetching the URI String, I will proceed with writing down the code and testing it. 

Below are the steps to fetch the URI from MongoDb Atlas, 

Step 1 – As I have guided already, You need to create an account in MongoDB Atlas. Then after creating an account you will be redirected to your account homepage(Refer to Image 1) where you will notice database deployment. Under that, cluster0 is created by default for you. 

Step 2 –  You need to click on connect tab present beside cluster0. When you click on it, a dialog will pop up giving you four options i.e., connect with shell, connect with your application, connect using MongoDB compass, and connect using VS Code. (Refer to Image

Step 3 – In this step, you need to select “connect your application”, and it will navigate you to the very next page of the dialog (Refer to Image 3) which will ask you to select your driver and its version. The driver is nothing but the language into which you want to integrate your connection string. Since we are working on Golang, we will select Golang as our driver and the latest version of it. This step will provide you with the connection string that you can integrate into your code. 

Step 4 – This is the last step to perform in MongoDB Atlas. Here, you need to copy down the string and save it on your clipboard. If you refer to “Image 3” below the string there is a message asking you to “Replace <password> with the password for the rishav_4waytechnologies user”. It means, rishav_4waytechnologies is my username, and in place of <Password> in the string, I need to give the password of my cluster. This is the process to fetch the connection string from MongoDB Atlas. 

While fetching my string and integrating it into my code, I was continuously facing errors in establishing the connection. While giving a thorough look into it, I found out that the password which, I have entered was not the actual password. Therefore, I had to change it. So please be cautious about it while fetching your connection string from MongoDB Cluster.  

In the next, I will be writing and explaining the code, but before proceeding you need to understand how to set your workspace, like creating directories, adding dependencies, etc

 

Getting Started with Golang

In this section, I will be guiding you on how, to begin with, the code but before that, I need to create my directory where the project will get stored. For creating the directory, I will open my command prompt and first check whether Golang is installed properly or not. I will type, “go” and it will show me “Go is a tool for managing Go source code”. This shows my go is installed properly and, this command will also provide me the list of commands below for my reference. 

Now let’s create the directory where my go files will get stored and proceed to check if it is connected to my database or not. 

I will guide you with some commands to create a directory, please refer below,

  • “cd Desktop”
  • “mkdir MongoConnect”
  • “cd MongoConnect”
  • “code .”

Here, the first command will push you from your main directory to your desktop directory where you need to enter the next command “mkdir MongoConnect” which creates a directory named “MongoConnection”. Here, I have named my workspace as MongoConnection, it totally depends on you, what name you want to create for your workspace. Now the third command instructs the system to push you into the directory you have created and finally, we will write “code .” which will open up your IDE which is Visual Studio Code in my case. Please refer to Image 4 and Image 5, which will give you a broader idea about the above explanation. 

Let’s begin with our code now, First step is to create our “main.go” file. The main.go file is a mandatory file for any Go program to get executed (Refer to Image 6). After creating main.go, you need to import some important packages in order to execute your Go program, but before that, you need to create go.mod file. For go.mod file you need to open up your terminal and write a command (“go mod init github.com/golangcompany/MongoConnect”). Then the first external package that you need to import is “go.mongodb.org/mongo-driver/mongo” and “go.mongodb.org/mongo-driver/mongo/options”. The external packages are basically the dependencies to initialize our Go program. Along with the external packages, you will require some internal packages of Go as well, like “Context” (Consider the following example to better understand the context package: suppose you are calling an API and it is not responding, and you do not want to wait all day for the response. As a result, you must stop the call or specify a timeout, which is handled by the context package.), “fmt” (Timeout implements formatted input or output; for instance, if you want to print something to the terminal, you import the fmt package.), “log” (The Go standard library has the Log package, which offers the most fundamental logging functionalities), and “time” (Here time package is used to measure, monitor, and display time). Please refer to Image 6 for further clarification. 

Now, hereafter importing the packages, I will start writing the code. To begin, I will write,

I have started with the main function from where our program will start. In that main function, my first step includes establishing a connection with MongoDB Cluster. The connection string that I have instructed you to copy from MongoDB Atlas needs to be integrated into the above line after ApplyURI. Here you need to mention the ID and password of the cluster in the string itself in order to run the code and establish the connection with the database. 

In the very next line, I have stated an “If” condition that instructs the program to log the error in case no connection is established. 

In the very line of code, I have written a code having a method (WithTimeout), for which the context package was imported initially. Basically, this instructs the program about the timeout. Let’s understand this with a real scenario. Suppose your application is trying to get connected to the database and there’s no time bound for it, so you won’t wait for the whole day, therefore we mention the timeout of 10 seconds to avoid these kinds of circumstances. In the above code defer cancel() is used when a function is returned to execution. It can be mentioned at the end of the code as well. In the next step, we will confirm our connection with Ping Method for that we write,

 

if there is any error after ping then the program will print failes to connect mongodband if there’s no error found then the program will print Successfully Connected to the mongodb”. 

Next, When I enter “go run main.go” in my terminal, it shows the following result, (Refer to

This is how you can establish a connection of your Go Application with MongoDB Atlas. Hope this was helpful for you.  

Leave a Reply