package main
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"time"
)
func main() {
// Set MongoDB connection string
connectionString := "mongodb://localhost:27017"
// Create a context with timeout
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
// Connect to MongoDB
client, err := mongo.Connect(ctx, options.Client().ApplyURI(connectionString))
if err != nil {
fmt.Println("Error connecting to MongoDB:", err)
return
}
defer func() {
// Disconnect from MongoDB when done
if err := client.Disconnect(ctx); err != nil {
fmt.Println("Error disconnecting from MongoDB:", err)
}
}()
// Ping MongoDB to check if the connection is successful
err = client.Ping(ctx, nil)
if err != nil {
fmt.Println("Error pinging MongoDB:", err)
return
}
fmt.Println("Connected to MongoDB")
}