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:
Import required packages:
context
,fmt
,log
,time
,go.mongodb.org/mongo-driver/mongo
,go.mongodb.org/mongo-driver/mongo/options
.Define the
main()
function.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 port27017
.Create a context with a timeout of 10 seconds using
context.WithTimeout
. This context will be used for connecting to MongoDB.Defer the cancellation of the context to ensure its release after the function execution using
defer cancel()
.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.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.Print "Connected to MongoDB!" if the connection is successful.