mongodb local connection string

package main

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

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

func main() {
    // Set the MongoDB connection string.
    clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")

    // Connect to MongoDB.
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()
    client, err := mongo.Connect(ctx, clientOptions)
    if err != nil {
        log.Fatal(err)
    }

    // Check the connection.
    err = client.Ping(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println("Connected to MongoDB!")
}

Explanation:

  1. Import required packages: context, fmt, log, time, go.mongodb.org/mongo-driver/mongo, go.mongodb.org/mongo-driver/mongo/options.

  2. Define the main() function.

  3. Set the MongoDB connection string using options.Client().ApplyURI("mongodb://localhost:27017"). This string specifies the connection to the MongoDB server running locally on the default port 27017.

  4. Create a context with a timeout of 10 seconds using context.WithTimeout. This context will be used for connecting to MongoDB.

  5. Defer the cancellation of the context to ensure its release after the function execution using defer cancel().

  6. Connect to MongoDB using mongo.Connect(ctx, clientOptions). This establishes a connection to the MongoDB server using the specified connection options. Any errors during connection establishment are captured.

  7. Check the connection to MongoDB by using client.Ping(ctx, nil). This sends a ping command to the server to verify the connection. Errors, if any, are handled.

  8. Print "Connected to MongoDB!" if the connection is successful.