Skip to content

Instantly share code, notes, and snippets.

@eduardohitek
Created September 2, 2023 12:19
Show Gist options
  • Save eduardohitek/000326c951ffce59bb03339b41e4d601 to your computer and use it in GitHub Desktop.
Save eduardohitek/000326c951ffce59bb03339b41e4d601 to your computer and use it in GitHub Desktop.
Logs in mongodb with Go
package main
import (
"context"
"log"
"log/slog"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/event"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
// MongoConfig holds the configuration for the MongoDB client.
type MongoConfig struct {
URL string
AppName string
DebugMode bool
Log slog.Logger
}
// createMongoClient creates a new MongoDB client.
func createMongoClient(cfg MongoConfig) (*mongo.Client, error) {
clientOptions := options.Client().ApplyURI(cfg.URL)
clientOptions.SetAppName(cfg.AppName)
if cfg.DebugMode {
monitor := &event.CommandMonitor{
Started: func(_ context.Context, e *event.CommandStartedEvent) {
if e.CommandName != "endSessions" {
cfg.Log.Info(e.Command.String())
}
},
}
clientOptions.SetMonitor(monitor)
}
client, err := mongo.Connect(context.Background(), clientOptions)
if err != nil {
return nil, err
}
return client, nil
}
func main() {
mongoCfg := MongoConfig{
URL: "mongodb://localhost:27017",
AppName: "MongoDB with query log",
DebugMode: true,
Log: *slog.Default(),
}
client, err := createMongoClient(mongoCfg)
if err != nil {
log.Fatal(err)
}
// Ping the MongoDB server to check if the connection was successful
err = client.Ping(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
// Insert a new document into the "users" collection
collection := client.Database("example-mongo").Collection("users")
_, err = collection.InsertOne(context.TODO(), bson.D{{Key: "name", Value: "Eduardo"}, {Key: "alias", Value: "eduardohitek"}, {Key: "site", Value: "https://eduardohitek.dev"}})
if err != nil {
log.Fatal(err)
}
// Find a document in the "users" collection
result := collection.FindOne(context.TODO(), bson.D{{Key: "alias", Value: "eduardohitek"}})
if err != nil {
log.Fatal(err)
}
resultInterface := bson.D{}
result.Decode(&resultInterface)
log.Println(resultInterface)
// Close the MongoDB client when done
err = client.Disconnect(context.TODO())
if err != nil {
log.Fatal(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment