DEV Community

Cover image for Integrating MONGODB in GOLANG applications
Kevin Wafula
Kevin Wafula

Posted on

Integrating MONGODB in GOLANG applications

Learning how to integrate no-sql databases with applications is becoming a must-know skill for all developers out there. Golang in particular provides the MongoDB Go Driver for easier and efficient connection with the mongo database.

In this article, I'll help you understand integration of the mongo database into Golang applications using the official MONGODB Go Driver.

  1. Getting started with MONGODB Go Driver

  2. CRUD operations with MongoDB

  3. Go structs and MongoDB Mapping

  4. Using Go structs to insert and Query MongoDB documents

Prerequisites

  • Some knowledge of Go

  • Should have installed MongoDB(version 3.6 or higher) compass locally on your desktop.

  • Go version 1.13 or higher installed

  • An IDE i.e. Visual studio

Getting started with MONGODB Go Driver
Let's install MongoDB Go driver which has functions that allow for connection to the MongoDB local database and execution of queries and operations.

The recommended method of installation is to use Go modules to install the dependency in your project. To install run

go get go.mongodb.org/mongo-driver/mongo
Enter fullscreen mode Exit fullscreen mode

Creating a MongoDB client instance

Create a main.go file and import the mongoDB Go driver package using the import statement. Next, Create a mongo Client using the connect function.

Image description

Advanced authentication and configuration can be found here.

To check if a server has been found and connected use ping:

Image description

Create a MongoDB Collection
Create collection instance retrieved from a user Collection named mongo-practice.If the database does not exist MongoDB will create it automatically when the above code is run.
Image description

Performing CRUD Operations with MongoDB

After connecting to the database and creating a Collection instance, we can now execute queries in our database using Go. This topic covers the crud(create, read, update and delete) operations.

To perform the CRUD operations, you need to add the `


go.mongodb.org/mongo-driver/bson

`
package to your import statement.

The go.mongodb.org/mongo-driver/bson package provides functionalities for working with BSON (Binary JSON) data, which is the encoding used to represent documents and data in MongoDB. BSON is a binary serialization format similar to JSON but designed for more efficient storage and traversal within the MongoDB database.

Inserting Documents in the Database

InsertOne executes an insert command to insert a single document into the collection.

Image description

In your terminal, run go run main.go. It should display something like this:

Image description
**InsertMany **executes an insert command to insert more than one document into the collection.

Image description

The results should be as follows:

Image description

Image description

Read Documents from the database

MongoDB provides FindOne() and Find() to retrieve documents from the database. FindOne() returns the first document that matches the filter while Find() returns all the documents that matches the filter.

The filter parameter must be a document containing query operators and can be used to select which documents are included in the result. It cannot be nil.

Opts parameter is used to specify the options.

Define a filter to find documents where age is greater than 25:

Image description

Find all documents that match the filter and Iterate through the cursor and print each document

Image description

Retrieve the first document that matches the filter and display the results.

Image description

Run go run .

Image description

Update Documents in MongoDB

MongoDB provides Update and Replace operations to change the documents in the database.

Other operations to change documents in the mongoDB database include:

  • UpdateByID()

  • UpdateOne()

  • UpdateMany()

  • ReplaceOne()

  • FindOneAndUpdate()

  • FindOneAndReplace()

UpdateByID() updates a single document with a specified ObjectID

Image description
Rungo main.go:
Image description

We first defined the document to insert and then Inserted the document into the "users" collection. Next Defined the update operation using the $set and $inc operators and finally updated the document using UpdateByID with the inserted document's ID.

UpdateOne() and UpdateMany()

First, define a filter documents where "age" is greater than 25.

Image description

Then define the update query using $set to update the "age" field:

Image description

Execute the UpdateOne() function to update the first matching document

Image description

Execute the UpdateMany() function to update all matching documents

Image description

ReplaceOne()

Define a filter to find the document with "name" equal to "Adrian"

Image description
Create the replacement data

Image description

Execute the ReplaceOne() function to replace the fields

Image description
Run go run main.go:

Image description

FindOneAndUpdate() and FindOneAndReplace() perform the same functions as FindOne() and ReplaceOne().The only difference is that they return the result before they update or replace.

Delete Documents from the database
DeleteOne and DeleteMany functions are provided by MongoDB to delete documents from the database.

First, let's define a filter to find documents where age is greater than 25.

Image description

Next, the first document that matches the filter
Image description

Finally, delete every document that matches the filter and display the number of documents deleted.

Image description

Go structs and MongoDB Mapping

MongoDB Go driver allows for working with Go structs. You can map documents to Go structs for easier data migrations and operations.

Here’s an example of struct matching the documents in the MongoDB database:

Image description

Using structs to insert MongoDb Documents

In this case, we create a school instance and insert the instance into the collection.

Image description
The results after running main.go:

Image description

Using Go structs to query MongoDb documents

For easier data accessibility you can query the MongoDB databases with Go structs.

First, execute a query to find documents that match the filter and move the cursor to the next document.

Image description

Next, define a School struct to store the decoded document and decode the document from the cursor into the School struct.

Finally, print the information about the school

Image description
The result when you run go run .:
Image description

Throughout the article, code examples, comments, and explanations provided a step-by-step guide for developers to follow along and understand the integration process. The article highlighted not only the technical aspects but also the importance of handling errors and checking for returned results.

In conclusion, mastering the integration of MongoDB with Go applications using the MongoDB Go Driver empowers developers to build robust and efficient applications that leverage the power of NoSQL databases. This article serves as a comprehensive introduction to this integration, equipping developers with the knowledge to enhance their skill set and create effective database-driven solutions.

For detailed and advanced concepts regarding MongoDB operations and aggregate functions ,you can head over to the MongoDB Driver documentation

Top comments (0)