How to use MongoDB in Golang applications

Golang MongoDB Tutorial

The demand for applications that use NoSQL-based databases is on the rise, with many developers looking to learn how to integrate databases like MongoDB into applications built with their favorite language and frameworks.

In this tutorial, I’ll teach you how to integrate MongoDB into Go applications by performing CRUD operations using the official MongoDB Go driver and providing code samples along the way.


To follow and understand this tutorial, you will need the following:

  • MongoDB installed on your machine
  • Working knowledge of Go
  • Go 1.x installed on your machine
  • A Go development environment (e.g., text editor, IDE)

Getting started with MongoDB

The first step is to install the MongoDB Go driver, the official Go driver for MongoDB. It provides functionalities that allow a Go application to connect to a MongoDB database and execute queries.

Set up your development environment

Create a new Go project in your text editor or IDE and initialize your go.mod file. You are free to use any name for your package:

go mod init mongo-with-golang
Go.Mod File After Initializing The Package

Install the MongoDB Golang driver

Install the MongoDB Golang driver package in your project. In the terminal, type the following:

go get
go get
Go.Mod File After Installing Mongo Go Driver

Create a MongoDB client instance

Import the Go driver package into your application, then create a MongoDB client instance for a database on port 27017 (MongoDB’s default port).