When the Agent Writes the Query: Injection and Exfiltration Paths in MongoDB
Content reflects the state as of November 2026. AI tooling and model capabilities in this area change frequently.
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
findonly on named collections (withjavascriptEnabled: false), and Queryable Encryption for sensitive fields.- Watch out: Granting the built-in
readrole on an entire database still lets$lookupread secret collections in that database, and MongoDB Community Edition lacks native database auditing.
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.
aggregate()blurs the read/write boundary via$outand$merge(TB-1 to TB-2). An agent tool namedrun_analytics_pipelineoften connects with areadWriteapplication 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.- Database-wide
readroles allow cross-collection$lookuppivots (TB-2). Even when teams use MongoDB’s built-inreadrole on a database ({ role: "read", db: "prod" }), that role grantsfindacross every collection inprod. An injected$lookup: { from: "api_tokens", ... }stage inside an aggregation onticketsjoins and exfiltratesapi_tokensin a single query. - Nested sub-pipelines and
$regexbypass naive stage checks (TB-1). Checking only top-level array keys for$outfails when attackers nest$lookupinside$facetor$unionWithsub-pipelines. Similarly, passing$regexinside afindfilter enables character-by-character blind extraction of secrets (^a,^ab) or CPU-exhausting ReDoS attacks unlessmaxTimeMSand operator allowlists are enforced. - Server-side JavaScript (
$where) executes arbitrary logic if enabled (TB-2). When server-side JavaScript is enabled onmongod,$whereand$functionevaluate 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.
How the Options Compare
| Capability | MongoDB Atlas (M10+ Dedicated) | Self-Managed Enterprise Advanced | Self-Managed Community Edition |
|---|---|---|---|
| Custom RBAC roles | Full support via Atlas UI / API / Terraform | Full support via mongosh (db.createRole) | Full support via mongosh (db.createRole) |
Server-side JS ($where) | Configurable / disabled per cluster settings | Disabled via security.javascriptEnabled: false in mongod.conf | Disabled via security.javascriptEnabled: false in mongod.conf |
| Queryable Encryption (QE) | Automatic QE out-of-the-box on 7.0+ clusters with AWS/GCP/Azure KMS | Automatic QE supported; requires managing crypt_shared or mongocryptd | Explicit encryption only (no automatic QE) |
| Native Database Auditing | Yes (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.
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 / Operator | Risk Class | Gateway Control (TB-1) | MongoDB Engine / Privilege Control (TB-2) |
|---|---|---|---|
$out, $merge | Arbitrary collection write / overwrite | Reject in recursive pipeline allowlist | Omit insert, update, remove actions from custom role |
$lookup, $graphLookup, $unionWith | Cross-collection data exfiltration | Block or restrict from to explicit allowlist | Grant find only on named collections—never DB-wide read |
$where, $function, $accumulator | Server-side JavaScript execution | Reject all JS operators in AST check | Set security.javascriptEnabled: false in mongod.conf |
$regex | Blind character extraction / ReDoS | Ban $regex in agent tools; use Atlas Search / indexed equality | Enforce maxTimeMS cap on every query and secondaryPreferred read preference |
$facet | Nested sub-pipeline smuggling | Recursively walk all sub-pipelines against the same stage allowlist | Custom role find boundaries still apply to every nested stage |
$ne, $gt, $exists | Filter bypass via type confusion | Enforce strict primitive types (Zod / JSON Schema); strip $ keys from user inputs | Prepend 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 Vector | Trust Boundary Crossed | Attacker Objective (OWASP / ATLAS) | Defender Control (Deterministic) | Verification Signal |
|---|---|---|---|---|
Injected $out / $merge stage | TB-1 → TB-2 (Pipeline → DB) | Overwrite or exfiltrate into writable collection (LLM06 / Impact) | Recursive stage allowlist + custom role with find only | Pipeline with $merge rejected at gateway and fails Unauthorized in DB |
Cross-collection $lookup pivot | TB-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 injection | TB-1 → TB-2 (Filter → Engine) | Execute arbitrary JS expressions inside mongod (Execution) | security.javascriptEnabled: false + strip $where in gateway | Query containing $where fails with no such cmd / disabled JS error |
Nested $facet stage smuggling | TB-1 (Agent → Gateway) | Hide $lookup inside $facet array to evade top-level check | Recursive AST walker inspects every nested array and sub-pipeline | Nested $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 fields | Strict JSON Schema / Zod primitive type checks + strip $ keys | Object passed for string parameter rejected before driver call |
| Plaintext PII in logs / agent context | TB-2 → TB-3 (DB → Agent) | Read sensitive customer fields via broad find projection | Queryable Encryption without KMS keys in agent + QE log redaction | Agent receives BinData ciphertext; server logs redact QE fields |
| ReDoS / unindexed collection scan | TB-2 (Query → Primary CPU) | Exhaust primary CPU via $regex or unindexed $match (Impact) | Ban $regex; require secondaryPreferred, maxTimeMS: 10000, $limit <= 100 | Slow 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.
Runtime Query Validation Flow
- 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. - 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. - 03 Scoped Execution: The gateway connects as
mcp_triage_agent(agent_tickets_ro) withreadPreference=secondaryPreferred,maxTimeMS=10000, and a$commentcontaining the caller’strace_id. - 04 Cap and Audit: Results are capped at
<= 100documents. Encrypted fields remainBinDataciphertext unless explicitly authorized, and Atlas/Enterprise auditing records the database operation alongside the gateway’s OIDC caller log.
Phased Rollout and Rollback Gates
- Phase 1 — Disable Server-Side JS and Inventory Roles: Set
security.javascriptEnabled: falseacross self-managed clusters (and verify Atlas settings). Audit all existing agent database users forreadWriteor DB-widereadroles. Gate: Zero agent accounts hold DB-widereadorreadWrite. Rollback: N/A (hardening baseline). - Phase 2 — Deploy Collection-Scoped Custom Roles: Create
agent_<domain>_roroles grantingfindstrictly on named collections, and switch MCP server connections tosecondaryPreferredwithmaxTimeMS. Gate: Cross-collection$lookupand$outtests fail at the database layer. Rollback: Temporarily add a missing collection to the custom role’sprivilegesarray via PR if a legitimate tool breaks. - Phase 3 — Enforce Recursive AST Validation in Gateway: Deploy primitive type checking,
$-key stripping, recursive stage allowlisting, and Stage-0 tenant$matchinjection. Gate: Nested$facet+$lookupred-team payload is blocked before reaching MongoDB. Rollback: Temporarily disable the free-form aggregation tool and fall back to pre-canned parameterizedfind()tools. - 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
BinDatafor 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/$mergeprivileges (Pattern A — Official Docs): Per the MongoDB Role-Based Access Control documentation, built-inreadgrantsfindacross all non-system collections in a database, whereas custom roles (db.createRole) restrictfindto explicit{ db, collection }resources and omitinsert/update/removeso$outand$mergeare blocked by the engine. - Server-side JavaScript and Queryable Encryption (Pattern A — Official Docs): Per MongoDB security configuration documentation, setting
security.javascriptEnabled: falsedisables$whereand 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 (
--auditDestinationand Atlas M10+ auditing) is available in Atlas and Enterprise Advanced, not in Community Edition.
Where It Breaks
| Condition | Breaks How | Detect | Mitigate |
|---|---|---|---|
Missing Stage-0 $match index | Prepending { $match: { tenant_id } } on an unindexed collection triggers full collection scans under load | explain("executionStats") shows COLLSCAN instead of IXSCAN | Create compound indexes leading with tenant_id on every multi-tenant collection |
| Agent holds KMS keys for Queryable Encryption | If the MCP gateway shares the app’s KMS role, the driver auto-decrypts PII into the LLM context | Agent response includes plaintext SSN/tokens despite QE enabled | Strip KMS Decrypt permissions from the agent/gateway IAM role; keep DEKs strictly in the core app |
| Community Edition lacks native audit trail | Incident responders cannot prove what an agent queried inside mongod if the gateway is bypassed | Audit gap during compliance review on self-managed Community clusters | Enforce private network isolation so only the auditing MCP gateway can reach mongod port 27017 |
| Dot-notation nested field probing | Attacker uses {"profile.secret_token": {"$exists": true}} to infer hidden subdocument fields | AST validator sees no $lookup but detects sensitive field paths | Allowlist permitted projection and filter field paths per collection in the gateway |
Replica lag on secondaryPreferred | Diagnostic agent reads stale state from a lagging secondary during an active incident | rs.printSecondaryReplicationInfo() shows lag exceeding SLA | Use 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
filterorpipelinearrays directly tofind()oraggregate()exposes$out,$merge,$lookup,$where, and$regex. - Never grant DB-wide
readorreadWriteto an agent: Define a custom role grantingfindstrictly on named collections so$out,$merge, and cross-collection$lookupfail insidemongod. - Disable server-side JavaScript: Set
security.javascriptEnabled: falseto eliminate$whereand$functionexecution paths. - Validate pipelines recursively: Walk nested stages (such as
$facet), enforce primitive types, strip$keys, and prepend a gateway-derivedtenant_id$matchas Stage 0. - Separate KMS decryption from agent identity: With Queryable Encryption, keeping KMS keys away from the agent ensures sensitive fields return as
BinDataciphertext and stay redacted in logs.
What to Do Next
- Problem: Agents generating MongoDB
find()oraggregate()payloads can pivot across collections via$lookup, overwrite data via$out/$merge, or probe secrets via$regex. - Solution: Replace broad
read/readWriteroles with collection-scopedfind-only custom roles, disable server-side JS, and enforce recursive pipeline allowlisting in your MCP gateway. - Proof: Submit a test pipeline containing a nested
$lookupto a sibling collection and a$mergestage; 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
readorreadWritegrants with collection-specific custom roles, and verifyjavascriptEnabled: falseon every cluster.