Working with MongoDB Using Golang

Implementing basic CRUD operations with Go and MongoDB using the mongo-go-driver

Radhakishan Surwase
Level Up Coding

--

Photo by Fabio on Unsplash

In this article, I will show you how to perform basic create, read, update & delete (CRUD) operations on the MongoDB database using Go. I am using the official MongoDB Go Driver for implementing the said operations.

Note: Before you go any further, I expect you all have a beginner level understanding of GoLang syntax and primitive types to understand the source-code. I also expect that you have a basic understanding of MongoDB concepts.

Install MongoDB Go Driver

Like the other official MongoDB drivers, the Go driver is idiomatic to the Go programming language. It provides an easy way to use MongoDB as the database solution for a Go program. It is fully integrated with the MongoDB API, and exposes all of the query, indexing, and aggregation features of the API, along with other advanced features. If you are using “go get”, you can install the driver using:

go get go.mongodb.org/mongo-driver

Create a database connection

I have implemented a package named connectionhelper that helps you to deal with the MongoDB database connection. The implementation of this package is explained below.

The code is self-explanatory. An important point to mention is that I have created a singleton object of MongoDB client using the “Once” object present in the sync package. Once is an object that will perform exactly one action. GetMongoClient() methods give you a MongoDB client object to work with. On the first call to GetMongoClient(), it creates and initializes the object of MongoDB client. Any subsequent calls to this function do not create a new client object they served with the previously created objects.

Define struct with bson tags

I have considered the Issue Manager application as an example. To work with the “Issue” entity present in the application I have defined the following struct

Listing 2: Define a structure to map documents.

The MongoDB drivers use the bson tags to map struct field to document attribute in the MongoDB collection. You are not required to specify and use bson tags, in which case the drivers usually just use the lowercased field names when encoding struct values. bson tags are required however when you need a different name. Throughout this article, I have used this struct in every code listing.

Add new document in the collection

To insert a single document, use the collection.InsertOne() method. The function CreateIssue() adds new documents in the collection and returns with boolean success status.

Listing 3: Implement Insert One Operation

To insert multiple documents at a time, the collection.InsertMany() the method will take a slice of objects. The function CreateMany() takes a slice of the struct Issue as input and inserts it into the collection.

Listing 4: Implement Insert Many Operation

Get a specific document from the collection.

To find a document, you will need a filter document as well as a pointer to a value into which the result can be decoded. To find a single document, use collection.FindOne(). This method returns a single result which can be decoded into a value. The function GetIssuesByCode takes code as an input parameter, compares it with the code field of documents, and returns the first matching document.

Listing 5: Implement Insert One Operation

Get all document from the collection

To find multiple documents, use collection.Find(). This method returns a Cursor. A Cursor provides a stream of documents through which you can iterate and decode one at a time. Once a Cursor has been exhausted, you should close the Cursor. The function GetAllIssues() returns all the documents present in the collection.

Listing 6: Implement Find All Operation

Update document in the collection

The collection.UpdateOne() method allows you to update a single document. It requires a filter document to match documents in the database and an updater document to describe the update operation. You can build these using bson.D types. The function MarkCompleted() takes ‘code’ as an input parameter, updates the first matching document & sets its completed flag to true.

Listing 7: Implement Update One Operation

Delete a document from the collection

Finally, you can delete documents using a collection.DeleteOne() or collection.DeleteMany(). Here you pass bson.D{{}} as the filter argument, which will match all documents in the collection. You could also use a collection.Drop() to delete an entire collection.

Listing 8: Implement Delete One Operation

The DeleteOne() method deletes only the first matching documents in the collection whereas DeleteMany() deletes all matching documents present in the collection.

Listing 8: Implement Delete Many Operation

The code for the connectionhelper package is here. You can find code for remaining CRUD operations here.

Conclusion

Over the course of this article, we have implemented basic CRUD operations. We learned about MongoDB Golang driver and its implementation in much better depth. The MongoDB Golang driver gives you a number of ways to interact with BSON data. The MongoDB Go Driver lets you integrate MongoDB into any application, and tap into the impressive Go ecosystem.

That's all for now. Happy Learning…. Keep Reading.

--

--

Innovative Golang Specialist | Golang Development | Scalable Architectures | Microservices | Docker | Kubernetes | Tech Writer | Programming Enthusiast