MongoDB

MongoDB is observed through the client span each command produces. This page lists the OpenTelemetry instrumentation for each language and how the command document is recorded.

The MongoDB driver in your application is instrumented by OpenTelemetry, and every command becomes a client span inside the trace of the request that issued it. Nothing is installed on the database, so the same setup applies to a self-hosted deployment, Atlas, and MongoDB-compatible services that the same driver connects to.

What is collected

SpanOne CLIENT span per command (find, insert, aggregate)
Identitydb.system.name = mongodb (db.system in instrumentation releases that predate the stable database conventions)
StatementThe command, reduced as described under Command text
TargetDatabase and collection name, server address and port
OutcomeDuration, and an error status when the command fails

The span reports how long the application waited for the driver. Which index was used and how many documents were examined are known only to the server and are not part of the span.

Enabling it

The Sophonz Node.js SDK loads the instrumentation for both mongodb (3.3 up to, not including, 8) and mongoose (5.9.7 up to, not including, 10). No configuration is needed.

The mongodb instrumentation creates a span only when a parent span is active, so commands issued outside a request, from a timer or at startup, produce nothing. The option is requireParentSpan.

import { init } from '@sophonz/node-sdk';
 
init({
  service: 'catalog-api',
  apiKey: process.env.SOPHONZ_API_KEY,
  instrumentations: {
    '@opentelemetry/instrumentation-mongodb': {
      requireParentSpan: false,
    },
  },
});

With Mongoose, both layers are active: a span for the Mongoose operation and one for the driver command under it.

Command text

A MongoDB command is a document, and its values are often user data.

LanguageDefault
Node.jsThe command document with every value replaced by ?, so the shape of the filter is kept and the data is not. enhancedDatabaseReporting: true records the values
PythonThe command name only. capture_statement: True records the command document
JavaSanitized. Values are replaced with ?

Leave value capture off outside development. A filter such as { email: "..." } otherwise stores the address with every span.

In Sophonz

Command spans sit under the request span in the trace, together with the browser or mobile session that started the request. They belong to the application's service: the Service Flow panel draws a node per service, so MongoDB does not appear as a node of its own.

Because the attributes are stored with the span, they can be queried in Grafana.

SELECT serviceName, name, count() AS calls, avg(durationNano) / 1e6 AS avg_ms
FROM sophonz_traces.distributed_sophonz_index_v2
WHERE $__timeFilter(timestamp)
  AND (stringTagMap['db.system.name'] = 'mongodb' OR stringTagMap['db.system'] = 'mongodb')
GROUP BY serviceName, name
ORDER BY avg_ms DESC
LIMIT 20