Better Programming

Advice for programmers.

Follow publication

Member-only story

How to Use Golang Structs With MongoDB

In this short example, I’ll show you how to create structs in the Go Language for use with MongoDB

Jes Fink-Jensen
Better Programming
Published in
6 min readApr 12, 2022

--

Photo by Ana Abad on Unsplash

To demonstrate the use of Golang structs with MongoDB, I have created a simple email autoresponder as an example. We have some contacts to whom we wish to send emails. In addition, we have emails to send at specific times, with subject and content. Lastly, we also have a sequence that connects the contacts to the emails.

By using Golang structs, we minimize the use of BSON in our code and increase the usability of the results from the database queries. This article can be seen as a continuation of a previous article called “How To Use Go With MongoDB.”

In what follows, I go over the code of a little demo, piece by piece.

Importing the relevant packages

To start, we’ll import the necessary Golang packages.

We need to import these libraries to do the following:

  • context is necessary to create a context for the MongoDB operations.
  • bson for serializing the data that is sent to the MongoDB server.
  • mongo to deal with connecting to the MongoDB server and setting up the database and collections.

Creating the structs

Instead of using bson serializations as we did in the previous article, the idea here is to use Golang structs. These structs need to use bson annotations for this to work correctly.

In the above piece of code, we can see various bson annotations.

These annotations all follow the same pattern:

--

--

No responses yet

Write a response