MongoDB provides Go lang drivers for connection to its document-oriented database.
here we are creating a folder(directory) for Go lang application, with folder name as mongodbconnection
mkdir mongodbconnection
cd mongodbconnection
initialize go module, by issuing the below command
go mod init github.com/freedomtutorials/mongodbconnection
on successful initialization, we will see below message
go: creating new go.mod: module github.com/freedomtutorials/mongodbconnection
Add MongoDB drivers to Go lang application, by issuing below command
go get go.mongodb.org/mongo-driver
on successful, the below output will be printed on console
go: added go.mongodb.org/mongo-driver v1.9.0
by this we have successfully installed mongo-driver in package module (go.mod), create a main file, place the below code in it.
package main
import (
"context"
"fmt"
"log"
// include mongodb drivers in application code
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func main() {
// set the mongodb uri, (the server ip : followed by port)
clientOptions := options.Client().ApplyURI("mongodb://127.0.0.1:27017")
//connect to mongodb server
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err)
}
err = client.Ping(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
fmt.Println("Application Connected to MongoDB!")
}
compile the code, by issuing the below command.
go build mongodbconnection.go
run the application, by issuing below command.
$ ./mongodbconnection
Application Connected to MongoDB!
Successfully Connected to MongoDB from Golang application.
how to use range in golang
posted on 2022-05-03 08:28:11 - Go lang Tutorials
find variable type in golang
posted on 2022-05-03 05:24:55 - Go lang Tutorials