Learn how to use MongoDB as a data source for your Go application using the mongo-go driver.
This tutorial assumes you have:
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.
First in an empty folder run the below command
go mod init gomongo
go 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.
package main
import (
"context"
"fmt"
"log"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
// Book - We will be using this Book type to perform crud operations
type Book struct {
Title string
Author string
ISBN string
Publisher string
Copies int
}
func main() {
// Set client options
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
// Connect to MongoDB
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err)
}
// Check the connection
err = client.Ping(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
fmt.Println("Connected to MongoDB!")
booksCollection := client.Database("testdb").Collection("books")
}
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
#go #mongodb #database #developer