Skip to main content

Overview

@kubiks/otel-mongodb provides comprehensive OpenTelemetry instrumentation for the MongoDB Node.js driver. Capture spans for all database operations with detailed metadata about collections, queries, and execution metrics.
MongoDB Trace Visualization
Visualize your MongoDB operations with detailed span information including collection names, operation types, and execution metrics.

Installation

Peer Dependencies: @opentelemetry/api >= 1.9.0, mongodb >= 5.0.0

Quick Start

instrumentMongoClient wraps the client you already use—no configuration changes needed. Every database operation creates a client span with useful attributes.

What Gets Traced

This instrumentation automatically traces all major MongoDB operations including:

Find Operations

find, findOne

Insert Operations

insertOne, insertMany

Update Operations

updateOne, updateMany, findOneAndUpdate

Delete Operations

deleteOne, deleteMany, findOneAndDelete

Aggregation

aggregate

Count Operations

countDocuments

Configuration

With Filter Capture

Filter capture is disabled by default to protect sensitive data. Only enable in secure, development environments or ensure filters don’t contain sensitive information.

Span Attributes

Each span includes rich metadata about the database operation following OpenTelemetry semantic conventions:
The instrumentation captures query metadata to help with debugging and monitoring, while optionally capturing filters based on your security requirements.

Usage Examples

Basic Find Operations

Insert Operations

Update Operations

Delete Operations

Aggregation Pipeline

Count Operations

Complete Integration Example

Here’s a complete example of MongoDB with OpenTelemetry in a Next.js application:

Setup

lib/mongodb.ts

Usage in Server Actions

app/actions/users.ts

Usage in API Routes

app/api/stats/route.ts

Best Practices

Always reuse the MongoDB client connection rather than creating new connections:
Only enable filter capture in development or when filters don’t contain sensitive data:
Ensure proper indexes are created for frequently queried fields:
Always handle MongoDB errors in your application:

Troubleshooting

Ensure OpenTelemetry is initialized before connecting to MongoDB:
Make sure your MongoDB URI is correct and the server is accessible:
Ensure you’ve configured peer information:

Resources

MongoDB Documentation

Learn more about MongoDB Node.js driver

GitHub Repository

View source code and examples

npm Package

View package on npm

Report Issues

Found a bug? Let us know!

License

MIT