Integrating MONGODB in GOLANG applications
Published: 2023-08-23 19:22:18

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](https://github.com/mongodb/mongo-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](https://github.com/mongodb/mongo-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
```

**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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7qlo3kzg1vrpr2m62vfm.png)



Advanced authentication and configuration can be found [here](https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#Connect).

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w5wevgvq9vlu94xac5nd.png)

**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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ucexdm9xzk00ya5ncbr1.png)

**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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m8ach3nv9l7bh4imvsfh.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wlxac7cuu3fryujj9wrr.png)
**InsertMany **executes an insert command to insert more than one document into the collection.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bi149dy36q8f5c7wdchm.png)

The results should be as follows:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/airm5sicwj0pjvc0meqq.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qbegm600pk4gcev3728l.png)


**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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6i9810a7p07a116cnmwg.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/utka77qfz8fv566fidxx.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hkm8gibzdvrw6i6zj0x5.png)

Run `go run .`

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v7hevamfn6vbs480u5o5.png)


**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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ubdydqxqe1m0qnseoox5.png)
Run` go main.go`:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d6wla0pwxartzc0tj0k2.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wckvt30ebtaedkky6exe.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xib4nm38lemtzh4i1xyt.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/forjaijfbtpa71laxle9.png)

Execute the UpdateMany() function to update all matching documents

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mz146phj9ighsujkphha.png)

**ReplaceOne()**

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pib90qz7yobrpbaf07q1.png)
Create the replacement data

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gy70o19ern3yqggtrf67.png)

Execute the ReplaceOne() function to replace the fields

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bshirov2pfidk05hv9pl.png)
Run `go run main.go`:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xu20evexxufd73y8msvx.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7g5retduq0hs8xbsf7b0.png)

Next, the first document that matches the filter
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dmb31hbzwh7ggecusoki.png)

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


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6d68g5c2cpi10zqc37on.png)

**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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8y8u6y2yjvsun519evvh.png)

**Using structs to insert MongoDb Documents**

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2z52z0uz72lz74q4fudi.png)
The results after running main.go:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g2bl9p5vcvssa1z8ixvg.png)


**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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jai87n5d5cyhafluus2q.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3tlewkdl01ctvq6ac9sx.png)
The result when you run `go run .`:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a1v8a8jvz50ynf3kfuuv.png)




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](https://docs.mongodb.com/) operations and aggregate functions ,you can head over to the [MongoDB Driver documentation](https://docs.mongodb.com/drivers/go/current/)