# MongoDB

> Instrument MongoDB Go applications with the Last9 Go Agent for automatic operation tracing and metrics

Source: https://last9.io/docs/integrations/frameworks/go/mongodb/

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

1. **Install the Last9 Go Agent**

   ```bash
   go get github.com/last9/go-agent
   ```

2. **Set Environment Variables**

   ```bash
   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"
   ```

3. **Instrument your application**

**New client**

   Use `mongoagent.NewClient()` instead of `mongo.Connect()`:

   ```go
   package main

   import (
       "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.M
       err = col.FindOne(context.Background(), bson.M{"name": "Alice"}).Decode(&result)
       if err != nil {
           log.Fatal(err)
       }

       log.Printf("found: %v", result)
   }
   ```

**Existing client options**

   Instrument an existing `*options.ClientOptions` — useful when you already have connection options configured:

   ```go
   package main

   import (
       "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 client
       client, 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:

```go
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 housekeeping
- `saslStart`, `saslContinue`, `authenticate` — auth handshakes
- `endSessions`

## 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](https://app.last9.io/traces) and [Metrics Explorer](https://app.last9.io/metrics) in Last9 to view your telemetry data.

---

## Troubleshooting

Please get in touch with us on [Discord](https://discord.com/invite/Q3p2EEucx9) or [Email](mailto:support@last9.io) if you have any questions.
