Loading

Set up MongoDB instrumentation

Package Supported versions
MongoDB.Driver ≥3.0.0 <4.0.0

For the full compatibility matrix including supported installation methods, refer to Data access technologies.

Note

MongoDB.Driver ≥3.7.0 natively emits OpenTelemetry spans. On runtimes where the agent's OpenTelemetry Bridge is supported, those spans are captured automatically, so no extra package is needed. On .NET Framework, the OpenTelemetry Bridge is not supported; use Elastic.Apm.MongoDb instead. This package is also required for MongoDB.Driver ≥3.0.0 <3.7.0.

The Elastic.Apm.MongoDb NuGet package instruments the official MongoDB.Driver to capture MongoDB operations as APM spans, including the command name, target database, and duration.

Note

If you are not already using Elastic.Apm.NetCoreAll, install Elastic.Apm.MongoDb. If you are using Elastic.Apm.NetCoreAll, you can skip this install step and continue with Step 2.

dotnet add package Elastic.Apm.MongoDb
		

Register the MongoDbEventSubscriber when creating your MongoClient:

using MongoDB.Driver;
using Elastic.Apm.MongoDb;

var settings = MongoClientSettings.FromConnectionString(mongoConnectionString);
settings.ClusterConfigurator = builder => builder.Subscribe(new MongoDbEventSubscriber());
var mongoClient = new MongoClient(settings);
		

How you complete the setup depends on how you added the APM agent to your application:

Using Elastic.Apm.NetCoreAll (the all-in-one package for ASP.NET Core) — no further action is needed. MongoDB calls are captured automatically on every active transaction.

Using Elastic.Apm.MongoDb directly — also subscribe the diagnostics subscriber once at application startup:

using Elastic.Apm;
using Elastic.Apm.MongoDb;

Agent.Subscribe(new MongoDbDiagnosticsSubscriber());
		

Make sure this is called only once. Calling it multiple times causes the agent to record duplicate spans for MongoDB operations.