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.
Getting started with MONGODB Go Driver
CRUD operations with MongoDB
Go structs and MongoDB Mapping
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
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.
Advanced authentication and configuration can be found here.
To check if a server has been found and connected use ping
:
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.
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.
In your terminal, run go run main.go
. It should display something like this:
**InsertMany **executes an insert command to insert more than one document into the collection.
The results should be as follows:
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:
Find all documents that match the filter and Iterate through the cursor and print each document
Retrieve the first document that matches the filter and display the results.
Run go run .
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
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.
Then define the update query using $set to update the "age" field:
Execute the UpdateOne() function to update the first matching document
Execute the UpdateMany() function to update all matching documents
ReplaceOne()
Define a filter to find the document with "name" equal to "Adrian"
Execute the ReplaceOne() function to replace the fields
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.
Next, the first document that matches the filter
Finally, delete every document that matches the filter and display the number of documents deleted.
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:
Using structs to insert MongoDb Documents
In this case, we create a school instance and insert the instance into the collection.
The results after running main.go:
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.
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
The result when you run go run .
:
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)