Using MongoDB as Datasource in GoLang
Learn how to use MongoDB as a data source for your Go application using the mongo-go driver


Learn How to Master Digital Trust

The State of Consumer Digital ID 2024

Top CIAM Platform 2024
Before You Get Started
This tutorial assumes you have:
- A basic understanding of Go Language
- Latest GoLang version installed on your system
- Latest MongoDB version installed on your system
In this tutorial, we will use the official MongoDB Go Driver to manage our MongoDB database. In the due process, we will write a program to learn how to install the MongoDB Go Driver and perform CRUD operations with it.
Installation
First in an empty folder run the below command
1go mod init gomongogo mod init creates a new go.mod file and automatically imports dependencies when you will run go program. Then create the file main.go and write the below code, We will explain what this code will do in a min.
1package main
2import (
3"context"
4"fmt"
5"log"
6"go.mongodb.org/mongo-driver/bson"
7"go.mongodb.org/mongo-driver/mongo"
8"go.mongodb.org/mongo-driver/mongo/options"
9
10)
11// Book - We will be using this Book type to perform crud operations
12type Book struct {
13Title string
14Author string
15ISBN string
16Publisher string
17Copies int
18}
19func main() {
20// Set client options
21clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
22// Connect to MongoDB
23client, err := mongo.Connect(context.TODO(), clientOptions)
24if err != nil {
25log.Fatal(err)
26}
27// Check the connection
28err = client.Ping(context.TODO(), nil)
29if err != nil {
30log.Fatal(err)
31}
32fmt.Println("Connected to MongoDB!")
33booksCollection := client.Database("testdb").Collection("books")
34}In the above code, we have imported the bson, mongo, and mongo/options packages of mongo-driver and defined a Book type which will be used in this tutorial
In the main function first, we created clientOptions with MongoDB URL and credentials and pass it to mongo.Connect function, Once connected we can check our connection by client.Ping function.
The following code will use booksCollection variable to query the books collection from testdb.
1booksCollection := client.Database("testdb").Collection("books")Insert Documents
First Let's create a Book struct to insert into the collection, in below code we are using collection.InsertOne function to insert a single document in the collection
1// Insert One document
2book1 := Book{"Animal Farm", "George Orwell", "0451526341", "Signet Classics", 100}
3insertResult, err := booksCollection.InsertOne(context.TODO(), book1)
4if err != nil {
5 log.Fatal(err)
6}
7fmt.Println("Inserted a single document: ", insertResult.InsertedID)To insert multiple documents at once we need to create a slice of Book object and pass it to collection.InsertMany
1// Insert multiple documents
2book2 := Book{"Super Freakonomics", "Steven D. Levitt", "0062312871", "HARPER COLLINS USA", 100}
3book3 := Book{"The Alchemist", "Paulo Coelho", "0062315005", "HarperOne", 100}
4multipleBooks := []interface{}{book2, book3}
5insertManyResult, err := booksCollection.InsertMany(context.TODO(), multipleBooks)
6if err != nil {
7log.Fatal(err)
8}
9fmt.Println("Inserted multiple documents: ", insertManyResult.InsertedIDs)Update Documents
We can update a single document by function collection.UpdateOne. It requires a filter document to match documents in the collection and an updated document to describe the update operation. You can build these using bson.D types. The below code will match the book with ISBN 0451526341 and increment the copies field by 10
1//Update one document
2filter := bson.D{{"isbn", "0451526341"}}
3update := bson.D{
4{"$inc", bson.D{
5{"copies", 10},
6}},
7}
8updateResult, err := booksCollection.UpdateOne(context.TODO(), filter, update)
9if err != nil {
10log.Fatal(err)
11}
12fmt.Printf("Matched %v documents and updated %v documents.\n", updateResult.MatchedCount, updateResult.ModifiedCount)You can also update more than one documents at once in a single collection by function
collection.UpdateMany, In it, we need to pass filter document and update document same ascollection.UpdateOne
Find Documents
To find a single document, we can use function collection.FindOne(), we will pass a filter document and decode the result in the Book type variable
1// A variable in which result will be decoded
2var result Book
3err = booksCollection.FindOne(context.TODO(), filter).Decode(&result)
4if err != nil {
5log.Fatal(err)
6}
7fmt.Printf("Found a single document: %+v\n", result)To find multiple documents, we use function collection.Find(). This method returns a Cursor, It provides a stream of documents on which we can iterate or we can get all the docs by function cursor.All() in a slice of Book type.
1cursor, err := booksCollection.Find(context.TODO(), bson.D{{}})
2if err != nil {
3 log.Fatal(err)
4}
5var books []Book
6if err = cursor.All(context.TODO(), &books); err != nil {
7 log.Fatal(err)
8}
9fmt.Printf("Found multiple documents: %+v\n", books)Delete Documents
We can delete documents from a collection using functions collection.DeleteOne() or collection.DeleteMany(). Here you pass bson.D{{}} as the filter argument, which will match all documents in the collection.
1deleteCollection, err := booksCollection.DeleteMany(context.TODO(), bson.D{{}})
2if err != nil {
3 log.Fatal(err)
4}
5fmt.Printf("Deleted %v documents in the books collection\n", deleteCollection.DeletedCount)Entire collection can be dropped using the collection.Drop() function, it will remove all documents and metadata, such as indexes from the collection
Once you have done all the operation, don't forget to close the MongoDB connection
1err = client.Disconnect(context.TODO())
2if err != nil {
3log.Fatal(err)
4}
5fmt.Println("Connection to MongoDB closed.")Now you can easily use MongoDB as Datasource in your go application, You can found the complete code used in this tutorial on our Github Repo
