DEV Community

Anurag Affection
Anurag Affection

Posted on • Updated on

Connecting MongoDB in Go - 03

  • First check the Go version by running the command
go version
Enter fullscreen mode Exit fullscreen mode
  • Create a folder
mkdir <folder_name>
Enter fullscreen mode Exit fullscreen mode
  • Switch to created folder
cd <folder_name>
Enter fullscreen mode Exit fullscreen mode
  • Initialize the go project by running the given command. You will get go.mod file.
go mod init <folder_name>
Enter fullscreen mode Exit fullscreen mode
  • Create a main.go file, use terminal or bash
notepad main.go 
touch main.go
Enter fullscreen mode Exit fullscreen mode
  • Let's write some basic code in main.go file.
package main 

import (
    "fmt"
)


func main() {
    fmt.Println("MongoDb with Go")
}

Enter fullscreen mode Exit fullscreen mode
  • Run the code by following command
go run main.go 
Enter fullscreen mode Exit fullscreen mode
  • You will see this output in console
MongoDb with Go
Enter fullscreen mode Exit fullscreen mode
  • Install some packages to connect MongoDB in Go. Here are commands
go get go.mongodb.org/mongo-driver
go get go.mongodb.org/mongo-driver/mongo
Enter fullscreen mode Exit fullscreen mode
  • Revisit the main.go file to connect MongoDB. This is our full code
package main

import (
    "context"
    "fmt"
    "log"

    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

// mongodb connections
var collection *mongo.Collection
var ctx = context.TODO()

func init() {
    clientOptions := options.Client().ApplyURI("mongodb://localhost:27017/")
    client, err := mongo.Connect(ctx, clientOptions)
    if err != nil {
        log.Fatal(err)
    }

    // check connection
    err = client.Ping(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("Connected to MongoDB!")

    collection = client.Database("testingWithGo").Collection("movies")
}

func main() {
    fmt.Println("MongoDb with Go")
}

Enter fullscreen mode Exit fullscreen mode
  • Run the code by following command again
go run main.go 
Enter fullscreen mode Exit fullscreen mode
  • You will see this output in console
Connected to MongoDB!
MongoDb with Go
Enter fullscreen mode Exit fullscreen mode

That's for today. Thank You .

Top comments (0)