Securing LLM-Assisted MongoDB Diagnostics: Profiler Data, Audit Logs and Operational Guardrails
Content reflects the state as of January 2026. AI tooling and model capabilities in this area change frequently.
MongoDB performance evidence can contain the data you are trying to protect. A read-only collector can still expose query literals, document fragments, tenant identifiers, client metadata, namespaces, and active operations long before an LLM recommends a change.
Technology and product capabilities in this series are evaluated as of June 30, 2026.
Situation
The first three MongoDB articles built incident evidence packs from host metrics, database diagnostics, query evidence, router targeting, and sharding state. That evidence can isolate cache pressure, expensive shapes, migration overhead, and hot shards.
It also crosses several security boundaries. The database profiler records operation detail in each database’s capped system.profile collection. $currentOp can expose command documents for active work. Diagnostic logs can include client-supplied data. An evidence export can outlive the short incident interval and move beyond MongoDB’s authorization boundary into object storage, an LLM service, review systems, and analyst devices.
The safe design is not “give the model read-only access.” It is to keep the model outside MongoDB and give it only a sanitized evidence product. Collection, reasoning, approval, execution, and validation remain separate capabilities.
The Problem
Read-only is necessary but insufficient. find on system.profile may reveal literals. The inprog privilege required for broad $currentOp visibility can expose other users’ operations. Even aggregates can identify customers through namespaces, comments, rare values, or tenant keys.
Security controls also differ by edition. MongoDB Enterprise includes the native auditing facility and redactClientLogData; they are not Community features. Native WiredTiger encryption at rest is Enterprise-only, and MongoDB documents that unencrypted audit and process log files are outside encrypted-storage-engine protection. A design that assumes those controls exist everywhere silently fails on Community deployments.
Finally, one log cannot prove the whole chain. MongoDB audit events can describe database activity, but they do not record the LLM’s evidence, prompt, recommendation, human approval, or external executor. Conversely, an AI audit trail cannot prove what the server accepted.
How do we retain enough evidence for diagnosis while preventing an analysis system from becoming a second privileged production interface?
Build a Separated MongoDB Diagnostic Control Plane
flowchart TD
A[MongoDB members and routers] --> B[read-only diagnostic collectors]
B --> C[restricted raw evidence zone]
C --> D[deterministic minimization and tokenization]
D --> E[sanitized incident evidence pack]
E --> F[LLM reasoning boundary]
F --> G[observations hypotheses gaps and proposed actions]
G --> H[human DBA approval]
H --> I[separate controlled executor]
I --> J[MongoDB validation evidence]
B --> K[collector and access audit]
F --> L[model and recommendation audit]
H --> M[approval and change audit]
I --> M
Use separate identities for collection, transformation, approval, and execution. The LLM has no MongoDB credential. The collector has no write, user-management, profiler-control, index-management, topology, or process-control authority. The executor cannot inherit continuous collector access.
Give every evidence field a contract: source, purpose, sensitivity, transformation, retention, model, owner, and deletion deadline. Separate raw and sanitized access domains. Record a manifest, checksum, and transformation version; only the sanitized pack is model-readable.
Symptoms
| Control failure | Operational signal | Required response |
|---|---|---|
| Profiler left enabled after capture | level or configuration differs from approved baseline | stop collection, restore prior state, assess exposure |
| Raw literals appear in evidence pack | redaction test or data-loss-prevention rule fails | quarantine pack and rotate exposed secrets if present |
| Collector can run a write command | negative authorization test unexpectedly succeeds | revoke identity and correct the role before reuse |
| Audit volume or latency jumps | overly broad filter or successful authorization auditing | narrow scope through reviewed Enterprise configuration |
| Missing profiler evidence on encrypted collection | Queryable Encryption redaction applies | use application and aggregate resource evidence |
| MongoDB action lacks model decision ID | audit planes cannot be joined | treat change as unapproved and investigate |
| Diagnostic log disappears during incident | rotation, retention, access, or sink failure | preserve host evidence and validate the logging pipeline |
First Five Checks
1. Inventory evidence before granting access
Classify metrics, $currentOp, diagnostic logs, system.profile, plans, configuration, metadata, and audit events separately. “Monitoring data” is not one sensitivity class.
Start with low-content aggregates. Add shapes only when they answer a hypothesis and raw commands only by exception. MongoDB 8.0 omits CRUD against Queryable Encryption collections from the slow-operation log and profiler and redacts parts of $currentOp; absence is not proof of no workload.
2. Build and test a diagnostic role
Inspect actual privileges with rolesInfo; do not infer least privilege from a role name. Prefer purpose-specific custom roles and separate database-scoped system.profile access from cluster actions such as serverStatus or inprog.
Test denials during deployment. The collector must fail attempts to change profiling, call setParameter, manage indexes or users, kill operations, alter topology or auditing, and read application collections. Restrict its network, require TLS and authentication, and forbid interactive use.
3. Bound profiler and log collection
Prefer existing diagnostic slow-operation logs before enabling the database profiler. Profiler state is per database and cannot be enabled on mongos; sharded collection is member-aware. Enabling it can affect performance and disk usage and can expose unencrypted query data.
If capture is approved, record prior settings, set an expiry, monitor overhead, and restore them. A filter replaces slowms and sampleRate behavior; level 2 captures all operations and ignores the threshold and filter, so deny it in routine production. Configuration changes reach the diagnostic log, but that mutable log is not an approval record.
Treat verbosity changes the same way. Raising component verbosity can disclose more client data and increase volume. redactClientLogData reduces that risk but also removes diagnostic detail, and it is Enterprise-only. Community deployments need stricter avoidance, collector-side parsing, and quarantine because they cannot rely on native log redaction.
4. Minimize before object storage and model access
Parse in the restricted raw zone. Allowlist fields. Replace literals with typed placeholders or incident-scoped tokens; remove payloads, credentials, connection strings, comments, network identifiers, tenant identifiers, user names, and free text unless approved.
Preserve UTC interval, process and role, namespace token, operation type, shape, plan summary, work counts, duration, waits, errors, and lineage. Keep the token map outside the model boundary. Scan for secrets, enforce schema limits, sign the manifest, and encrypt the pack.
Object-store retention is independent of system.profile being capped. Apply automatic expiry to raw and sanitized objects, replicas, search indexes, prompt traces, caches, backups, and review exports. Deletion must be testable rather than assumed from the primary object disappearing.
5. Audit the decision and database action separately
MongoDB Enterprise auditing can record authentication, authorization, schema, replica-set, sharding, and selected CRUD activity. Successful CRUD authorization auditing requires auditAuthorizationSuccess, which MongoDB warns has greater performance impact; use reviewed filters and load testing. MongoDB 8.0 can emit its native audit schema or OCSF. Community process, application, proxy, and OS logs are useful compensating evidence but are not equivalent to the Enterprise database audit facility.
Export audit evidence to a protected central sink with restricted readers, retention, integrity monitoring, and synchronized clocks. MongoDB documents that buffered events can be lost on termination and audit-destination write failure terminates the server. Syslog may truncate messages undetected.
Join two planes with an incident and decision ID. The AI plane records evidence-pack hash, transformation and prompt versions, model, output, reviewer, approval, expiry, and rejected alternatives. The database plane records authenticated principal, client metadata, command, target, result, and time. Neither plane alone proves authorization and execution.
Decision Tree
flowchart TD
A[diagnostic evidence requested] --> B{aggregates answer the question}
B -->|yes| C[collect minimal read-only evidence]
B -->|no| D{operation detail is necessary}
D -->|no| E[reject expanded collection]
D -->|yes| F{approved scope role and expiry exist}
F -->|no| E
F -->|yes| G[bounded log or profiler capture]
G --> H[allowlist tokenize scan and seal]
H --> I{sanitization tests pass}
I -->|no| J[quarantine and investigate]
I -->|yes| K[LLM analysis without database credential]
K --> L{production action proposed}
L -->|no| M[record diagnostic conclusion]
L -->|yes| N[human approval and separate executor]
In Practice
A collector can retrieve command detail from system.profile, so “read-only” does not mean “non-sensitive.” $currentOp broadens visibility when inprog is granted. The model boundary therefore belongs after deterministic minimization.
Edition differences also change the architecture. Enterprise can redact client data from process logs and emit native audit events, but redaction sacrifices diagnostic content and auditing can add load. Community needs a more conservative collection envelope and external access records. The documented pattern is to record these as different assurance levels, not label both “audited.”
Queryable Encryption creates the opposite risk: protected collections can remove operations and fields from diagnostic sources. The LLM must identify this as missing evidence and shift to application latency, resource counters, sanitized client telemetry, and controlled reproduction—not conclude that the collection was idle.
Remediation Options
- Replace a broad built-in role with tested custom diagnostic roles split by source and database.
- Default to level
0slow-operation logging; use time-bounded level1profiling only when approved evidence gaps justify it. - Add an allowlist transformer, typed tokenization, secret scanning, schema validation, and pack expiry before model integration.
- On Enterprise, evaluate client-log redaction and narrowly filtered auditing with measured diagnostic and performance tradeoffs.
- On Community, strengthen application attribution, OS access logging, centralized log protection, and collector audits while explicitly documenting the native-audit gap.
- Put every production command behind a separate executor that validates an approved command template, target, parameters, evidence hash, expiry, and rollback plan.
Rollback Plan
Before capture, store prior profiler and verbosity settings, owner, expiry, and restoration command. Automatic cleanup must run even if analysis fails. Verify every affected mongod; one successful restoration is not cluster-wide rollback.
For role changes, preserve the prior role definition, deploy a parallel replacement identity, prove required reads and prohibited actions, move the collector, then revoke the old principal. For audit-filter changes, canary where the topology and compliance policy allow, measure event volume and latency, and retain the prior configuration. Remember that failure to write the audit destination can stop the server.
If sensitive evidence crosses the model boundary, revoke access, quarantine derived objects, preserve the security incident trail, determine vendor retention and deletion scope, rotate any exposed secrets, and notify the accountable privacy or security owner. Deleting the prompt alone is not containment.
Where It Breaks
| Failure mode | Why the guardrail fails | Required control |
|---|---|---|
| LLM shares the collector credential | prompt content can drive database reads | no model-network path or database secret |
| Redaction occurs after upload | raw data already crossed the boundary | transform inside restricted zone |
| Stable global tokens replace literals | tokens become cross-incident identifiers | incident-scoped tokens and isolated map |
| Capped profiler collection implies deletion | copies persist in exports and backups | end-to-end retention inventory |
| Audit success enabled without filters | volume and server cost can surge | measured scope and performance limits |
| Syslog treated as lossless | messages may be truncated | destination-aware integrity checks |
| Community logs called native audit | evidence semantics and coverage differ | label the assurance gap explicitly |
| Queryable Encryption omission read as inactivity | security redaction creates false absence | mark missing evidence and use other layers |
What the LLM Cannot Do
The LLM cannot authenticate to MongoDB, browse application documents, enable profiling, increase log verbosity, alter audit controls, run unbounded explain() execution, kill operations, create or drop indexes, change query settings, alter replica or sharding configuration, disable security controls, or execute a remediation. It may analyze a sanitized pack, distinguish facts from hypotheses, request approved evidence, propose a bounded diagnostic, and draft a change plan for human review.
These restrictions must be enforced by credentials, network policy, command allowlists, workflow state, expiry, and independent auditing—not by a system prompt.
What to Do Next
- Problem: MongoDB diagnostic evidence can expose production data and operational authority even when collection is read-only.
- Solution: Separate identities and audit planes, minimize evidence before model access, and encode edition-specific controls and gaps.
- Proof: Test forbidden commands, profiler expiry, redaction, secret detection, encrypted-collection gaps, audit coverage, sink failure, object deletion, stale approvals, and emergency revocation.
- Action: Build the MongoDB evidence registry and negative-authorization suite before connecting an LLM. The next track applies the same evidence-first method to Valkey on EC2 and Amazon ElastiCache.
Sources
- MongoDB 8.0 — Database profiler configuration
- MongoDB 8.0 — Database profiler output
- MongoDB 8.0 —
$currentOp - MongoDB 8.0 — Built-in roles
- MongoDB 8.0 — Role-based access control
- MongoDB 8.0 — Auditing
- MongoDB 8.0 — Self-managed configuration options
- MongoDB 8.0 — Log messages and redaction
- MongoDB 8.0 — Queryable Encryption limitations
- MongoDB 8.0 — Security checklist for self-managed deployments