Member-only story
How To Use Go With MongoDB
Connect to a MongoDB server and perform basic CRUD operations with the Go language (Golang)
In this article, I will give you an introduction to using Golang with MongoDB. First, I’ll show you how to install MongoDB and important Golang packages.
Then, we’ll connect to a MongoDB server, ping it, and list the existing databases. After that, I’ll go over an example where I use various functions for performing CRUD operations.
Installing MongoDB and Golang Packages
Installing MongoDB for your platform is pretty straightforward. You can get the community edition from here.
Given that I’m working on windows, I had the option of installing MongoDB as a service. I choose not to do this because I use MongoDB as a test server. However, the result is that I need to start MongoDB manually.
Manual starting of MongoDB on windows
To start the MongoDB server manually, you can do the following:
- First, make sure there is a data directory in your path from where you are running the command — in the example below, it’s
./data
. - Then run
"C:\Program Files\MongoDB\Server\5.0\bin\mongod" — dbpath ./data
in your terminal. Your path may be slightly different. In this case, you can search formongod
and see what the path may be on your system.
The MongoDB Compass desktop app
You can also install MongoDB Compass. Get it here.
This desktop app can help you manage and audit the data you enter into the MongoDB server.
This is very handy for testing purposes as this app lets you see which databases, collections, and documents have been created.
The server address and password
For the rest of this article, my MongoDB database server will be running at the address mongodb://localhost:27017
.
As the database is just for exploring and testing ideas in Golang, I did not put a username and password on the database server.