Go lang
Programs
read csv file
find variable type in golang
for loops in golang
MongoDB sort() Method
MongoDB Find
MongoDB FindOne
differences between arrays and slices
InsertOne MongoDB
Connecting to MongoDB
how to use range in golang
Modules
Create a Go module
Create app using Go Module
Install
Installing GO lang

Connecting to MongoDB from Go lang



Connecting to MongoDB from Go lang

MongoDB provides Go lang drivers for connection to its document-oriented database.


Create Folder for Application

here we are creating a folder(directory) for Go lang application, with folder name as mongodbconnection


mkdir mongodbconnection
cd mongodbconnection


init go mod

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

how to use range in golang

posted on 2022-05-03 08:28:11 - Go lang Tutorials


find variable type in golang

find variable type in golang

posted on 2022-05-03 05:24:55 - Go lang Tutorials


for loops in golang

for loops in golang

posted on 2022-05-03 04:27:40 - Go lang Tutorials


Run MongoDB On WSL Ubuntu

Run MongoDB On WSL Ubuntu

posted on 2022-04-28 05:02:09 - mongodb Tutorials


Installing MongoDB

Installing MongoDB

posted on 2022-04-28 04:16:57 - mongodb Tutorials


MySQL TRIGGERS

MySQL - Triggers

posted on 2019-11-29 21:44:07 - mysql Tutorials