Connect to MongoDB in Golang

We show you the code to connect to MongoDB in Golang. But before running this example, you need to have a database and a collection to connect. The following exercise was executed with the help of Visual Studio Code and MongoDB Compass

ยป More Golang Examples

go mod init

Having MongoDB correctly installed, we start the server with the port set by default with the following command in the terminal:


After we generate a local database in Compass:

Connect to MongoDB in Golang

We will also create a database and as required, a new collection.

Connect to MongoDB in Golang

Finally in our collection we insert a new document with test data.

  "name":"Sophia Whatson",
  "name":"James Hopkins",

Connect to MongoDB in Golang

Now the code:

package main

import (



// const AccessDataMongoDB = "mongodb://min01:min01@" + ipServer + ":27017/?authSource=cfdis&readPreference=primary&appname=MongoDB%20Compass&directConnection=true&ssl=false"
const AccessDataMongoDB = "mongodb://docker:mongopw@"

var clientMongoDB *mongo.Client

func InitMDB() {
	clientOptions := options.Client().ApplyURI(AccessDataMongoDB)

	var err error
	clientMongoDB, err = mongo.Connect(context.TODO(), clientOptions)
	if err != nil {

	//Check the connections
	err = clientMongoDB.Ping(context.TODO(), nil)
	if err != nil {

To get the libraries execute the following command inside the terminal of your project in Visual Studio Code:

go get

If you got an error with git, you can try running the following code:

sudo apt-get install git

Having as a final result the following:

We hope this example of how to Connect to MongoDB in Golang will help you.