Let’s try MongoDB in Go

Gilang Prambudi
DSC Esa Unggul
Published in
5 min readAug 16, 2020

Harness the simplicity of NoSQL database with Mongo, combined with the simplicity of Go.

A Go-Gopher in front of a MongoDB schema. Picture combined from https://camo.githubusercontent.com & https://mongodb.com

A brief introduction to MongoDB

MongoDB is a general purpose, document-based, distributed database built for modern application developers and for the cloud era. As what the official web says. Unlike other structured database like MySQL, Postgres or Oracle, MongoDB doesn’t force us to create a well-structured schema or table. Instead, it use a JSON-like document that contain dynamic structure. Take a look at the illustration below:

A common SQL Schema relation

The same Schema, but in MongoDB

If you want to study more about Mongo, you may visit the official web https://docs.mongodb.com/. The web provide a well documented guiding for you to learn about MongoDB

Today’s use case : Dead Simple To Do Service

We will create a basic To Do service, where the data will be stored in MongoDB. FYI, To Do Service is a service where you can store your “going to do activity” in database and retrieve it back to the client. But, for the sake of relevancy, we will put behind the client app and create the back-end service only.

First thing first : Install MongoDB

Make sure you have installed MongoDB server and configured the credential (if needed). Follow the guide in this website, according to your Operating System.

But, if you really want to exactly follow this tutorial, you can install MongoDB on Docker like me. (Note that prior knowledge to Docker is needed)

https://docs.mongodb.com/manual/tutorial/install-mongodb-enterprise-with-docker/

Create the project structure

Create a new Go module, name it to todo_service_mongo

go mod init todo_service_mongo

And, this is the project structure:

Now, let’s code!

Initializing main package and creating MongoDB instance connection

Install MongoDB driver for Go

go get go.mongodb.org/mongo-driver/mongo

Now, initialize this basic instance to be consumed by the modules:

  1. MongoDB Client
  2. MongoDB Database instance
  3. HTTP Server

Put it in main.go

In the code above, I create a client connection to MongoDB by setting the 3 paramater:

MongoDB URI (ApplyURI) host address of MongoDB instance. MongoDB default Port is 27017

MongoDB Credential (SetAuth) as the credential for my Admin user. Yours maybe different, if you don’t set any auth, you may remove the function call

MongoDB Max Pool Size (SetMaxPoolSize) as the maximum pool size of active connection that MongoDB can handle concurrently (I think, the default is set around 100). When our app larger, and we have more concurrent connection running, we can increase this number to handler more concurrent MongoDB process

And the rest, I start HTTP server on port :4021

Create Model

Model (domain entity) will map the field of our Todo, write this code into models/todo.go

Note, that we specify a 3rd party data type in DocumentID. It is because in MongoDB, we don’t need to specify primary key, as there already a built-in primary key in field _id that automatically created every time we create new document, and that field has a primitive MongoDB data type called ObjectID. So, DocumentID will be our identifier for MongoDB Todo data.

Setting Up Repository

Now, we create a Repository interface and it’s MongoDB implementation for Todo module.

Write this in modules/repository.go:

And the implementation in modules/todoRepository/mongoRepository.go:

Now create the Use case a.k.a the Interactors. This package is the place where business logic happens.

Create the interface, write this code in modules/todo/usecase.go

Create the implementation of the interface, write this code in modules/todo/todoUseCase/todoUseCase.go

We have set up the repository layer. Now our job is to declare the HTTP Handler, and bundle it up by injecting the dependency of each layer

Create HTTP Delivery (Handler)

a.k.a Presenter layer. This package will handle the HTTP Request coming from client. Write this code in modules/todo/todoDelivery/httpDelivery.go

Now let’s initialize the Dependency Injection of Todo module in main.go. The final main.go will look like this:

I added in line 46 to 49, the dependency injection used to initialize Todo module. You can look the final source code in my GitHub too:

API Testing

After the code complete, now we will test if it really works. In this scenario, I will use Postman to test the API. In case if you don’t know Postman yet, it is a very useful tool developer should have. You can create various HTTP request by this tool (Get, Post, Put, Patch, Delete, etc). You can also create an automation test for your API.

Learn more about Postman in the official website : https://www.postman.com/

Make sure to run the Todo service first, by typing this command:

go run main.go

Test #1 : Insert new Todo

In postman, I create new POST request pointing on : http://localhost:4021/api/todo

It seems to work. I add more Todo(s) after that

Test #2 : Get All Todo(s)

I create new GET request pointing on : http://localhost:4021/api/todo

Work as expected, Proceed.

Test #3 : Update existing Todo

I create new PUT request pointing on : http://localhost:4021/api/todo

I think, it’s not a good day to watch Die Hard. Let’s change it to other chill movie

Work like a charm

Test #4 : Delete existing Todo

Finally, I create new DELETE request pointing on : http://localhost:4021/api/todo

And, it’s gone.

Conclusion

That’s all for this chapter. It should be noted that both SQL and NoSQL database have it’s Pro(s) and con(s). I will not describe them here. But, what ever you do, do it according to your use case. NoSQL may be good at storing unstructured Geo-spatial data where SQL may be good at storing most of conventional web data.

--

--

Gilang Prambudi
DSC Esa Unggul

I prefer old-school song and technology, as they are obvious and more understandable.