An LLM generating MongoDB aggregation pipelines can turn a “read-only” analytics endpoint into a cross-collection exfiltration or collection-overwriting attack if your gateway passes raw JSON stages and your database role grants database-wide read or readWrite.

TL;DR

  • Problem: MongoDB queries are JSON/BSON documents where operators ($where, $regex) and aggregation stages ($lookup, $out, $merge) live inside the same structure as user data—allowing prompt injection to pivot across collections or overwrite data.
  • Answer: Combine four deterministic layers: strict primitive type validation in the MCP gateway, a recursive pipeline stage allowlist, a custom MongoDB role granting find only on named collections (with javascriptEnabled: false), and Queryable Encryption for sensitive fields.
  • Watch out: Granting the built-in read role on an entire database still lets $lookup read secret collections in that database, and MongoDB Community Edition lacks native database auditing.

Generated pipelines reach write stages and hidden collections

Situation

Teams building natural-language analytics or support triage agents over MongoDB often expose an MCP tool that accepts a JSON filter or pipeline array generated by the LLM and passes it straight to collection.find() or collection.aggregate(). Because there is no SQL string concatenation, developers frequently assume NoSQL queries are immune to injection.

In reality, MongoDB’s query language is an abstract syntax tree encoded as JSON. If an indirect prompt injection inside a support ticket (Post 1, Post 2) coerces the LLM into emitting $lookup, $out, $merge, $regex, or $where inside that JSON payload, the driver executes it faithfully. Unlike a relational SELECT statement—which is syntactically incapable of writing to a table—MongoDB’s aggregate() method supports both read stages and write stages ($out, $merge) in the same API call. Even simple find() filters become an exfiltration vector when an LLM swaps an expected scalar value for an operator object like {"$regex": "^sk_live_"}, turning boolean match counts or latency differences into a character-by-character oracle.

Across MongoDB Atlas and self-managed MongoDB (Enterprise Advanced vs. Community), the exact privileges, server-side JavaScript controls, Queryable Encryption capabilities, and native auditing differ sharply, so the security boundary must be designed across both the gateway and the database engine.

The Problem

Passing model-generated JSON filters or aggregation pipelines to MongoDB without structural validation and collection-scoped RBAC breaks across four concrete boundaries.

Agent-generated MongoDB queries cross three boundaries

  1. aggregate() blurs the read/write boundary via $out and $merge (TB-1 to TB-2). An agent tool named run_analytics_pipeline often connects with a readWrite application role. If an attacker injects a final $out: "public_reports" or $merge: { into: "users" } stage into the pipeline array, a supposedly read-only analytics call overwrites or creates collections on the primary.
  2. Database-wide read roles allow cross-collection $lookup pivots (TB-2). Even when teams use MongoDB’s built-in read role on a database ({ role: "read", db: "prod" }), that role grants find across every collection in prod. An injected $lookup: { from: "api_tokens", ... } stage inside an aggregation on tickets joins and exfiltrates api_tokens in a single query.
  3. Nested sub-pipelines and $regex bypass naive stage checks (TB-1). Checking only top-level array keys for $out fails when attackers nest $lookup inside $facet or $unionWith sub-pipelines. Similarly, passing $regex inside a find filter enables character-by-character blind extraction of secrets (^a, ^ab) or CPU-exhausting ReDoS attacks unless maxTimeMS and operator allowlists are enforced.
  4. Server-side JavaScript ($where) executes arbitrary logic if enabled (TB-2). When server-side JavaScript is enabled on mongod, $where and $function evaluate JavaScript expressions against documents, turning injected strings into arbitrary code execution inside the database process.

How do you let an agent query MongoDB collections for diagnostics or analytics without letting generated operators pivot across collections, overwrite data, or leak encrypted fields?

Options Considered: Atlas vs. Self-Managed Enterprise vs. Community

Before writing roles and gateway validators, compare how MongoDB’s deployment editions support encryption, JavaScript lockdown, and native auditing.

Atlas and self-managed MongoDB differ on auditing and encryption

How the Options Compare

CapabilityMongoDB Atlas (M10+ Dedicated)Self-Managed Enterprise AdvancedSelf-Managed Community Edition
Custom RBAC rolesFull support via Atlas UI / API / TerraformFull support via mongosh (db.createRole)Full support via mongosh (db.createRole)
Server-side JS ($where)Configurable / disabled per cluster settingsDisabled via security.javascriptEnabled: false in mongod.confDisabled via security.javascriptEnabled: false in mongod.conf
Queryable Encryption (QE)Automatic QE out-of-the-box on 7.0+ clusters with AWS/GCP/Azure KMSAutomatic QE supported; requires managing crypt_shared or mongocryptdExplicit encryption only (no automatic QE)
Native Database AuditingYes (M10+ clusters; custom JSON audit filters + SIEM export)Yes (--auditDestination file/syslog, JSON/BSON filters)No native auditing (must log at MCP gateway / proxy; profiler is not a security log)

If your compliance model requires tamper-evident database-level security audit logs alongside automatic Queryable Encryption, MongoDB Atlas (M10+) or Self-Managed Enterprise Advanced is required. On Atlas M10+ clusters, you can attach custom JSON audit filters through the Atlas UI or API to log authentication events, authorization failures, and CRUD queries for mcp_triage_agent while shipping logs directly to SIEM tools or cloud event buses. On Self-Managed Enterprise Advanced, --auditDestination file --auditFormat JSON captures equivalent mongod and mongos events—though in sharded clusters, auditing must be enabled on every mongos, config server, and shard mongod to avoid blind spots. On Community Edition, the database profiler (db.setProfilingLevel()) records slow queries for performance tuning, not authentication or authorization events, so the MCP Policy Gateway must act as the authoritative audit log and sit inside a private network segment that blocks direct client access to mongod.

Four-Layer Guardrail Architecture

The target architecture enforces defense-in-depth across four layers so that bypassing any single check does not expose data or allow writes.

Four guardrail layers block MongoDB injection and exfiltration

Mapping Risky Stages and Operators to Controls

Every dangerous MongoDB operator or aggregation stage maps to a deterministic gateway rule and a database-level privilege or configuration setting. Relying on only one layer leaves a single-point-of-failure gap if a schema validator is bypassed or a driver configuration drifts. In addition to role boundaries, enforce strict timeout and read-preference defaults (maxTimeMS and secondaryPreferred) on the driver connection string itself:

Stage / OperatorRisk ClassGateway Control (TB-1)MongoDB Engine / Privilege Control (TB-2)
$out, $mergeArbitrary collection write / overwriteReject in recursive pipeline allowlistOmit insert, update, remove actions from custom role
$lookup, $graphLookup, $unionWithCross-collection data exfiltrationBlock or restrict from to explicit allowlistGrant find only on named collections—never DB-wide read
$where, $function, $accumulatorServer-side JavaScript executionReject all JS operators in AST checkSet security.javascriptEnabled: false in mongod.conf
$regexBlind character extraction / ReDoSBan $regex in agent tools; use Atlas Search / indexed equalityEnforce maxTimeMS cap on every query and secondaryPreferred read preference
$facetNested sub-pipeline smugglingRecursively walk all sub-pipelines against the same stage allowlistCustom role find boundaries still apply to every nested stage
$ne, $gt, $existsFilter bypass via type confusionEnforce strict primitive types (Zod / JSON Schema); strip $ keys from user inputsPrepend gateway-derived { $match: { tenant_id } } as Stage 0

Custom Collection-Scoped Role Definition

Never assign the built-in read or readWrite roles to an AI agent. Instead, define a custom role (agent_tickets_ro) scoped strictly to the find action on the exact collections the agent is authorized to read—excluding admin, config, local, and sibling sensitive collections such as api_tokens or users:

// Run on the target database (e.g., support_db) as userAdmin
db.createRole({
  role: "agent_tickets_ro",
  privileges: [
    {
      resource: { db: "support_db", collection: "tickets" },
      actions: [ "find" ]
    }
  ],
  roles: []
});

db.createUser({
  user: "mcp_triage_agent",
  pwd: "<rotated-via-secrets-manager-or-oidc>",
  roles: [ { role: "agent_tickets_ro", db: "support_db" } ]
});

Because agent_tickets_ro holds only find on support_db.tickets and zero insert, update, or remove actions, any $out or $merge stage fails with an authorization error even if a bug in the gateway lets it through. Note why both write stages matter: $out replaces an entire target collection (or creates a new one), while $merge can selectively insert, update, or replace matching documents in an existing collection—meaning a single injected $merge stage can corrupt specific user records or elevate flags without triggering a full collection drop. Likewise, any $lookup targeting support_db.api_tokens fails immediately at mongod because the role has no find privilege on api_tokens.

For sensitive fields inside tickets (such as ssn or payment_token), enable Queryable Encryption (QE). Unlike server-side $redact or $project pipeline stages—which only hide fields after the query executes and can be bypassed if an agent alters its own projection—QE encrypts fields on the client before they ever leave the core application. When the agent’s MongoDB driver connects without the client-side KMS Data Encryption Keys (DEKs), MongoDB returns BinData ciphertext for encrypted fields, and automatically redacts those fields from diagnostic commands and server logs. On Atlas 7.0+ dedicated clusters, automatic QE works out of the box with AWS KMS, GCP KMS, or Azure Key Vault; on Self-Managed Enterprise Advanced, you must deploy the crypt_shared library (or mongocryptd) alongside the application tier that performs encryption, while keeping the agent tier completely unconfigured for KMS decryption.

Finally, pair the custom role with explicit resource bounds on every driver call: set readPreference=secondaryPreferred so analytical scans do not contend with primary writes, attach maxTimeMS: 10000 so an expensive $group or unindexed sort aborts at 10 seconds, and inject $comment: "trace_id=..." so every query in mongod logs or the Atlas profiler maps back to the exact OIDC caller.

Attacker and Defender Threat Matrix

Threat VectorTrust Boundary CrossedAttacker Objective (OWASP / ATLAS)Defender Control (Deterministic)Verification Signal
Injected $out / $merge stageTB-1 → TB-2 (Pipeline → DB)Overwrite or exfiltrate into writable collection (LLM06 / Impact)Recursive stage allowlist + custom role with find onlyPipeline with $merge rejected at gateway and fails Unauthorized in DB
Cross-collection $lookup pivotTB-2 (Collection → Sibling)Read api_tokens or users via tickets aggregation (Collection)Grant find on tickets only; never grant DB-wide read$lookup to api_tokens returns not authorized on support_db
$where server-side JS injectionTB-1 → TB-2 (Filter → Engine)Execute arbitrary JS expressions inside mongod (Execution)security.javascriptEnabled: false + strip $where in gatewayQuery containing $where fails with no such cmd / disabled JS error
Nested $facet stage smugglingTB-1 (Agent → Gateway)Hide $lookup inside $facet array to evade top-level checkRecursive AST walker inspects every nested array and sub-pipelineNested $lookup inside $facet rejected with HTTP 400 at gateway
Type confusion ($ne / $regex)TB-1 (Input → Query)Pass {"$regex": "^s"} instead of string to probe fieldsStrict JSON Schema / Zod primitive type checks + strip $ keysObject passed for string parameter rejected before driver call
Plaintext PII in logs / agent contextTB-2 → TB-3 (DB → Agent)Read sensitive customer fields via broad find projectionQueryable Encryption without KMS keys in agent + QE log redactionAgent receives BinData ciphertext; server logs redact QE fields
ReDoS / unindexed collection scanTB-2 (Query → Primary CPU)Exhaust primary CPU via $regex or unindexed $match (Impact)Ban $regex; require secondaryPreferred, maxTimeMS: 10000, $limit <= 100Slow synthetic query aborts at 10s on secondary; primary unaffected

How It Rolls Out

A four-step validation pipeline ensures every generated query is type-checked, tenant-scoped, and bounded before it touches MongoDB.

Validate pipeline stages recursively before MongoDB sees them

Runtime Query Validation Flow

  1. 01 Type Check: The MCP gateway validates all tool arguments with strict primitive schemas (rejecting JSON objects where strings or integers are expected) and strips any key beginning with $ or containing . from user-supplied parameters.
  2. 02 Walk Pipeline: If the tool builds an aggregation pipeline, a recursive AST validator verifies that every stage—including nested stages inside $facet—is in the explicit allowlist ($match, $group, $sort, $project, $limit). The gateway then prepends { $match: { tenant_id: verified_oidc_tenant } } as Stage 0.
  3. 03 Scoped Execution: The gateway connects as mcp_triage_agent (agent_tickets_ro) with readPreference=secondaryPreferred, maxTimeMS=10000, and a $comment containing the caller’s trace_id.
  4. 04 Cap and Audit: Results are capped at <= 100 documents. Encrypted fields remain BinData ciphertext unless explicitly authorized, and Atlas/Enterprise auditing records the database operation alongside the gateway’s OIDC caller log.

Phased Rollout and Rollback Gates

  1. Phase 1 — Disable Server-Side JS and Inventory Roles: Set security.javascriptEnabled: false across self-managed clusters (and verify Atlas settings). Audit all existing agent database users for readWrite or DB-wide read roles. Gate: Zero agent accounts hold DB-wide read or readWrite. Rollback: N/A (hardening baseline).
  2. Phase 2 — Deploy Collection-Scoped Custom Roles: Create agent_<domain>_ro roles granting find strictly on named collections, and switch MCP server connections to secondaryPreferred with maxTimeMS. Gate: Cross-collection $lookup and $out tests fail at the database layer. Rollback: Temporarily add a missing collection to the custom role’s privileges array via PR if a legitimate tool breaks.
  3. Phase 3 — Enforce Recursive AST Validation in Gateway: Deploy primitive type checking, $-key stripping, recursive stage allowlisting, and Stage-0 tenant $match injection. Gate: Nested $facet + $lookup red-team payload is blocked before reaching MongoDB. Rollback: Temporarily disable the free-form aggregation tool and fall back to pre-canned parameterized find() tools.
  4. Phase 4 — Enable Queryable Encryption and Audit Streaming: Move sensitive PII fields to Queryable Encryption (without granting agent access to KMS DEKs) and stream Atlas/Enterprise audit logs to your SIEM. Gate: Agent queries return BinData for encrypted fields; audit logs correlate every query to a trace ID. Rollback: Keep gateway redaction active if QE schema migration is still in progress.

In Practice

I have not audited every MongoDB Community and Enterprise deployment topology personally, so the controls above are grounded in official MongoDB documentation and established NoSQL injection mechanics:

  • Built-in vs. custom roles and $out/$merge privileges (Pattern A — Official Docs): Per the MongoDB Role-Based Access Control documentation, built-in read grants find across all non-system collections in a database, whereas custom roles (db.createRole) restrict find to explicit { db, collection } resources and omit insert/update/remove so $out and $merge are blocked by the engine.
  • Server-side JavaScript and Queryable Encryption (Pattern A — Official Docs): Per MongoDB security configuration documentation, setting security.javascriptEnabled: false disables $where and server-side JS execution; Queryable Encryption (GA in MongoDB 7.0+ on Atlas and Enterprise Advanced) encrypts sensitive fields client-side, so the server stores and queries them without seeing plaintext.
  • Auditing availability (Pattern A — Official Docs): Per MongoDB Auditing documentation, native database auditing (--auditDestination and Atlas M10+ auditing) is available in Atlas and Enterprise Advanced, not in Community Edition.

Where It Breaks

MongoDB queries fail via $out writes, $lookup pivots, and $regex

ConditionBreaks HowDetectMitigate
Missing Stage-0 $match indexPrepending { $match: { tenant_id } } on an unindexed collection triggers full collection scans under loadexplain("executionStats") shows COLLSCAN instead of IXSCANCreate compound indexes leading with tenant_id on every multi-tenant collection
Agent holds KMS keys for Queryable EncryptionIf the MCP gateway shares the app’s KMS role, the driver auto-decrypts PII into the LLM contextAgent response includes plaintext SSN/tokens despite QE enabledStrip KMS Decrypt permissions from the agent/gateway IAM role; keep DEKs strictly in the core app
Community Edition lacks native audit trailIncident responders cannot prove what an agent queried inside mongod if the gateway is bypassedAudit gap during compliance review on self-managed Community clustersEnforce private network isolation so only the auditing MCP gateway can reach mongod port 27017
Dot-notation nested field probingAttacker uses {"profile.secret_token": {"$exists": true}} to infer hidden subdocument fieldsAST validator sees no $lookup but detects sensitive field pathsAllowlist permitted projection and filter field paths per collection in the gateway
Replica lag on secondaryPreferredDiagnostic agent reads stale state from a lagging secondary during an active incidentrs.printSecondaryReplicationInfo() shows lag exceeding SLAUse readPreference=secondaryPreferred with maxStalenessSeconds or route urgent triage to Atlas Telemetry APIs

Key Takeaways

  • MongoDB queries are JSON ASTs, not safe strings: Passing model-generated filter or pipeline arrays directly to find() or aggregate() exposes $out, $merge, $lookup, $where, and $regex.
  • Never grant DB-wide read or readWrite to an agent: Define a custom role granting find strictly on named collections so $out, $merge, and cross-collection $lookup fail inside mongod.
  • Disable server-side JavaScript: Set security.javascriptEnabled: false to eliminate $where and $function execution paths.
  • Validate pipelines recursively: Walk nested stages (such as $facet), enforce primitive types, strip $ keys, and prepend a gateway-derived tenant_id $match as Stage 0.
  • Separate KMS decryption from agent identity: With Queryable Encryption, keeping KMS keys away from the agent ensures sensitive fields return as BinData ciphertext and stay redacted in logs.

What to Do Next

  • Problem: Agents generating MongoDB find() or aggregate() payloads can pivot across collections via $lookup, overwrite data via $out/$merge, or probe secrets via $regex.
  • Solution: Replace broad read/readWrite roles with collection-scoped find-only custom roles, disable server-side JS, and enforce recursive pipeline allowlisting in your MCP gateway.
  • Proof: Submit a test pipeline containing a nested $lookup to a sibling collection and a $merge stage; verify the gateway rejects both and that direct DB execution under the custom role fails authorization.
  • Action: Audit your MongoDB agent roles this week, replace any DB-wide read or readWrite grants with collection-specific custom roles, and verify javascriptEnabled: false on every cluster.