MongoDB
Instrument MongoDB Go applications with the Last9 Go Agent for automatic operation tracing and metrics
Use the Last9 Go Agent to instrument MongoDB operations with automatic tracing and metrics. All CRUD operations, aggregation pipelines, and index operations are traced. Connection housekeeping commands (hello, ping, isMaster) and auth handshakes are silently skipped.
Prerequisites
- Go 1.22 or higher
- MongoDB Go driver v1 (
go.mongodb.org/mongo-driver) - Last9 account with OTLP credentials
Installation
-
Install the Last9 Go Agent
go get github.com/last9/go-agent -
Set Environment Variables
export OTEL_SERVICE_NAME="your-service"export OTEL_EXPORTER_OTLP_ENDPOINT="$last9_otlp_endpoint"export OTEL_EXPORTER_OTLP_HEADERS="Authorization=$last9_otlp_auth_header"export OTEL_TRACES_SAMPLER="always_on"export OTEL_RESOURCE_ATTRIBUTES="deployment.environment=production" -
Instrument your application
Use
mongoagent.NewClient()instead ofmongo.Connect():package mainimport ("context""log""go.mongodb.org/mongo-driver/bson""github.com/last9/go-agent"mongoagent "github.com/last9/go-agent/integrations/mongodb")func main() {if err := agent.Start(); err != nil {log.Fatalf("failed to start agent: %v", err)}defer agent.Shutdown()client, err := mongoagent.NewClient(mongoagent.Config{URI: "mongodb://localhost:27017",})if err != nil {log.Fatal(err)}defer client.Disconnect(context.Background())col := client.Database("mydb").Collection("users")// All operations are automatically traced_, err = col.InsertOne(context.Background(), bson.M{"name": "Alice", "age": 30})if err != nil {log.Fatal(err)}var result bson.Merr = col.FindOne(context.Background(), bson.M{"name": "Alice"}).Decode(&result)if err != nil {log.Fatal(err)}log.Printf("found: %v", result)}Instrument an existing
*options.ClientOptions— useful when you already have connection options configured:package mainimport ("context""log""os""go.mongodb.org/mongo-driver/mongo/options""github.com/last9/go-agent"mongoagent "github.com/last9/go-agent/integrations/mongodb")func main() {if err := agent.Start(); err != nil {log.Fatalf("failed to start agent: %v", err)}defer agent.Shutdown()opts := options.Client().ApplyURI(os.Getenv("MONGO_URI"))opts.SetAuth(options.Credential{Username: "admin",Password: os.Getenv("MONGO_PASSWORD"),})// Instrument the options — returns a fully connected clientclient, err := mongoagent.Instrument(opts)if err != nil {log.Fatal(err)}defer client.Disconnect(context.Background())col := client.Database("mydb").Collection("orders")// All operations are automatically traced}
What Gets Traced
All CRUD operations are traced automatically:
col := client.Database("mydb").Collection("products")ctx := context.Background()
// All of these produce spans:col.InsertOne(ctx, bson.M{"name": "Widget", "price": 9.99})col.InsertMany(ctx, []interface{}{bson.M{"name": "A"}, bson.M{"name": "B"}})col.Find(ctx, bson.M{"price": bson.M{"$gt": 5.0}})col.FindOne(ctx, bson.M{"_id": id})col.UpdateOne(ctx, bson.M{"_id": id}, bson.M{"$set": bson.M{"price": 12.99}})col.DeleteOne(ctx, bson.M{"_id": id})col.Aggregate(ctx, mongo.Pipeline{...})col.Indexes().CreateOne(ctx, mongo.IndexModel{...})Commands that are skipped (noise reduction):
hello,isMaster,ping— connection housekeepingsaslStart,saslContinue,authenticate— auth handshakesendSessions
Span Attributes
Each traced operation includes:
| Attribute | Example |
|---|---|
db.system | mongodb |
db.name | mydb |
db.operation | find, insert, update |
db.mongodb.collection | users |
db.statement | sanitized command document |
server.address | localhost |
server.port | 27017 |
What Gets Measured Automatically
| Metric | Description |
|---|---|
db.mongodb.operations | Total operation count by operation type |
db.mongodb.errors | Failed operation count |
db.mongodb.operation.duration | Duration histogram in milliseconds |
View Traces and Metrics
After running your application, navigate to Trace Explorer and Metrics Explorer in Last9 to view your telemetry data.
Troubleshooting
Please get in touch with us on Discord or Email if you have any questions.