Golang connect to mongodb | Go

 package main

import (
    "context"
    "fmt"
    "log"
    "time"

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

func main() {
    client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://your_username:your_password@localhost:27017"))
    if err != nil {
        log.Fatal(err)
    }
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()
    err = client.Connect(ctx)
    if err != nil {
        log.Fatal(err)
    }
    defer client.Disconnect(ctx)

    fmt.Println("Successfully connected to MongoDB!")
} 

AI Explanation

This Go program establishes a connection to a MongoDB database using the official MongoDB Go driver. Here's a breakdown of the code: 1. The program imports necessary packages including context, fmt, log, time, and the MongoDB driver packages. 2. In the `main()` function: - It creates a new MongoDB client using `mongo.NewClient()` with options specifying the connection URI. This URI includes a username, password, and address of the MongoDB server. - If there's an error in creating the client, it logs the error and exits. - It then initializes a context with a timeout of 10 seconds. - The program attempts to connect to the MongoDB server using the client's `Connect()` method with the timeout context. If an error occurs during the connection, it logs the error and exits. - If the connection is successful, it prints "Successfully connected to MongoDB!". - Finally, it defers disconnecting the client using `Disconnect()` method with the context. 3. The connection URI in `ApplyURI()` function should be modified to include the actual username, password, and the correct address of the MongoDB server. 4. The program demonstrates connecting to a MongoDB database in Go, handling errors, and ensuring proper disconnection from the database after the operation. Overall, this code snippet demonstrates a basic connection setup to MongoDB using Go.