MongoDB Queryable Encryption solves a problem that standard encryption-at-rest and standard field-level encryption cannot: it allows the database server to evaluate a query predicate against an encrypted field without the server ever holding the field’s plaintext. Standard encryption-at-rest encrypts the storage layer — but decrypts every page into memory the moment a query accesses it. Standard field-level encryption (FLE v1) stores ciphertext at rest but requires the client to fetch documents and decrypt them before any field-level filtering can occur. Queryable Encryption (QE, also called FLE2 internally) is a third model: the client sends a cryptographically structured query token; the server evaluates the token against a specialized metadata index without decrypting the field; the server returns matching documents in ciphertext; the client decrypts the results. The server never sees plaintext for any QE-encrypted field, at any point in the query lifecycle.

This distinction matters specifically when the threat model includes privileged database access: DBAs with db.auth() credentials, MongoDB Atlas operational staff with infrastructure access, or an attacker who compromises the mongod process. Under standard encryption-at-rest, all these actors can query and read plaintext. Under QE, they see only ciphertext — bounded by the cryptographic scheme, not by access controls.

Situation

MongoDB Queryable Encryption reached General Availability in MongoDB 7.0 (GA 2023-08-15) for equality queries. MongoDB 8.0 (GA 2024-10-02) expanded the supported query types to include range queries with configurable precision. Understanding the architecture requires distinguishing between the three encryption schemes MongoDB provides:

Encryption SchemeServer SeesServer Can QueryThreat Model Protected AgainstAvailable Since
Encryption-at-rest (WiredTiger)Plaintext in memory during queriesFull query capabilityStolen storage media, offline backup theftMongoDB 3.2+ (WiredTiger default)
FLE v1 — Explicit Client-Side EncryptionCiphertext stored, but client must fetch+decrypt before filteringNo server-side filtering on encrypted fieldsStorage theft only — not privileged DB accessMongoDB 4.2
QE (FLE v2) — Queryable EncryptionCiphertext only — never decrypted on serverEquality and range queries via structured encryptionStorage theft AND privileged database access during normal operationMongoDB 7.0 (equality), 8.0 (range)
In-Use Encryption (future)——Full homomorphic — arbitrary queriesNot yet GA

The threat model that QE is specifically designed for: a regulated enterprise where the database team, cloud provider, or infrastructure operators must be excluded from reading sensitive field values (SSN, salary, medical record IDs, PII) while the application must still be able to query those fields efficiently — without fetching entire collections to the application layer for in-memory filtering.

The Problem

Understanding QE’s constraints requires understanding what the server is actually doing when it evaluates an encrypted query — and why the scheme cannot be extended to arbitrary query types without fundamentally changing the cryptographic foundation.

Standard AEAD (Authenticated Encryption with Associated Data) encryption — the basis for FLE v1 — uses a random nonce per encryption operation, producing a different ciphertext for the same plaintext every time. This is a security property: identical plaintexts produce different ciphertexts, preventing frequency analysis. But it also means the server has no way to determine whether two encrypted values are equal — the ciphertexts are opaque to the server.

QE uses a different cryptographic primitive: a structured encryption scheme (specifically, a form of order-revealing encryption for range queries and deterministic encryption for equality). The server can evaluate equality by comparing encrypted tokens without learning the underlying plaintext. Range queries are supported through a specialized range tree structure that allows order comparisons on ciphertext — but only within the precision and bounds declared at field creation time.

The operational consequence: QE field constraints are immutable at creation time. A field created with queryType: "equality" cannot later have range query support added without dropping and recreating the collection (including re-encrypting all documents). Teams that implement QE without thoroughly mapping all future query patterns against each field are building schema debt into an encrypted layer where migrations are expensive.

How do you architect QE field declarations to satisfy both current and anticipated query requirements, and what are the exact cryptographic boundaries that determine which query types can never be server-side evaluated?

The FLE2 Cryptographic Architecture: DEK Hierarchy, libmongocrypt, and Metadata Indexes

The envelope key hierarchy. QE uses a two-tier key architecture:

flowchart TD
    CMK[Customer Master Key — CMK — stored in KMS — AWS KMS — Azure Key Vault — GCP KMS] --> DEK[Data Encryption Key — DEK — encrypted by CMK — stored in key vault collection]
    DEK --> FC[Field-level encryption — each QE field encrypted with its own DEK]
    FC --> EQ[Equality ciphertext — deterministic per plaintext — stored in document]
    FC --> META[Metadata index entries — encrypted bloom filter tokens — stored in __safeContent__ array]

The Customer Master Key (CMK) never leaves the KMS. The Data Encryption Key (DEK) is a per-field or per-collection key that is: generated client-side, encrypted using the CMK via KMS API, and stored encrypted in a key vault collection in the same MongoDB database or a separate cluster. The DEK is fetched from the key vault and decrypted by the KMS at query time — meaning two round-trips to KMS are required for each unique DEK used in a query: one to fetch the encrypted DEK from MongoDB, one to decrypt the DEK via KMS.

The cryptographic separation is the security property: an attacker with access to the MongoDB database sees the encrypted DEK in the key vault collection but cannot decrypt it without KMS access. An attacker with KMS access but no MongoDB access has the decryption capability but no ciphertext. Compromising either layer alone does not expose plaintext.

libmongocrypt — the encryption proxy. QE is implemented in libmongocrypt, a C library embedded in MongoDB drivers (Node.js, Python, Java, Go, .NET, etc.). When the application sends a query against a QE-encrypted field, the driver intercepts the operation before it reaches the wire, passes it to libmongocrypt, which:

  1. Fetches the DEK for the field from the key vault collection (MongoDB read)
  2. Decrypts the DEK using the configured KMS provider (KMS API call)
  3. Encrypts the query predicate value using the DEK and the appropriate QE scheme (deterministic for equality, range tree for range)
  4. Substitutes the encrypted token into the query document
  5. Sends the encrypted query to the server

The server receives and evaluates the encrypted query against the stored ciphertext. This interception is transparent to the application — the application uses standard MongoDB query syntax; libmongocrypt handles the transformation.

Metadata indexes — the __safeContent__ array. For equality queries, QE stores deterministic ciphertext (the same plaintext produces the same ciphertext) directly in the document field. The server compares ciphertexts directly using its standard B-Tree index. For range queries, QE stores a __safeContent__ array on each document — an array of encrypted bloom filter tokens that encode the range position of the field value within the declared min/max bounds. The server queries this array using a specialized range metadata index to identify documents whose range tokens match the query range.

The __safeContent__ array is automatically maintained by libmongocrypt — it is not application-visible and should not be manually modified. Modifying it breaks the range query evaluation without producing an error — queries return incorrect results silently.

In Practice

Setting up QE — field map declaration. The encrypted fields map is the most consequential configuration decision in a QE deployment:

// Python with pymongo — QE collection creation
from pymongo import MongoClient
from pymongo.encryption import ClientEncryption
from pymongo.encryption_options import AutoEncryptionOpts

# Key vault collection (stores encrypted DEKs)
KEY_VAULT_NAMESPACE = "encryption.__keyVault"

# KMS provider configuration — AWS KMS example
kms_providers = {
    "aws": {
        "accessKeyId": os.environ["AWS_ACCESS_KEY_ID"],
        "secretAccessKey": os.environ["AWS_SECRET_ACCESS_KEY"],
    }
}

# CMK ARN — the Customer Master Key in AWS KMS
cmk_arn = "arn:aws:kms:us-east-1:123456789:key/your-cmk-key-id"

# Create ClientEncryption object for key operations
client_encryption = ClientEncryption(
    kms_providers=kms_providers,
    key_vault_namespace=KEY_VAULT_NAMESPACE,
    key_vault_client=MongoClient(MONGODB_URI),
    codec_options=CodecOptions(uuid_representation=STANDARD),
)

# Create a DEK for the SSN field (stored encrypted in key vault)
ssn_dek_id = client_encryption.create_data_key(
    "aws",
    master_key={"key": cmk_arn, "region": "us-east-1"},
    key_alt_names=["ssn-field-key"]  # Named key for easier reference
)

# Create a DEK for the salary field
salary_dek_id = client_encryption.create_data_key(
    "aws",
    master_key={"key": cmk_arn, "region": "us-east-1"},
    key_alt_names=["salary-field-key"]
)

# Encrypted fields map — define per-field encryption parameters
encrypted_fields_map = {
    "encrypted_hr.employees": {
        "fields": [
            {
                "path": "ssn",
                "bsonType": "string",
                "keyId": ssn_dek_id,
                "queries": [{"queryType": "equality"}]
                # NOTE: equality uses deterministic encryption
                # The same SSN always produces the same ciphertext
                # This allows equality comparison without decryption
            },
            {
                "path": "salary",
                "bsonType": "int",
                "keyId": salary_dek_id,
                "queries": [{
                    "queryType": "range",
                    "min": 0,
                    "max": 5000000,  # Must encompass all actual salary values
                    "sparsity": 1,   # Tree depth: lower = fewer false positives, larger index
                    "trimFactor": 6  # Controls bloom filter density (MongoDB 8.0+)
                }]
            },
            {
                # Fields without a "queries" entry are encrypted but NOT queryable server-side
                "path": "medical_record_id",
                "bsonType": "string",
                "keyId": ssn_dek_id,
                # No "queries" key — this field is encrypted but never queried on server
            }
        ]
    }
}

# Auto-encryption options — libmongocrypt intercepts queries transparently
auto_encryption_opts = AutoEncryptionOpts(
    kms_providers=kms_providers,
    key_vault_namespace=KEY_VAULT_NAMESPACE,
    encrypted_fields_map=encrypted_fields_map,
)

# Client with auto-encryption enabled
encrypted_client = MongoClient(MONGODB_URI, auto_encryption_opts=auto_encryption_opts)

Querying QE-encrypted fields. The application uses standard MongoDB query syntax — the driver’s libmongocrypt intercepts and transforms the query transparently:

# Standard MongoDB query — libmongocrypt encrypts the predicate before sending
# Find employees with a specific SSN (equality query)
employee = encrypted_client["encrypted_hr"]["employees"].find_one(
    {"ssn": "123-45-6789"}   # libmongocrypt encrypts "123-45-6789" using SSN DEK before send
)
# Server receives: {"ssn": BinData(6, "<encrypted_token>")}
# Server evaluates equality on encrypted tokens — no plaintext on server

# Range query on salary (range query — requires range queryType configured above)
high_earners = list(encrypted_client["encrypted_hr"]["employees"].find(
    {"salary": {"$gte": 200000, "$lte": 500000}}
))
# libmongocrypt converts to range tokens using the salary DEK and range scheme

Verifying encryption at rest — server perspective. Connecting to MongoDB without encryption configuration shows only ciphertext:

// Unencrypted connection — what the DBA / attacker sees
use encrypted_hr
db.employees.findOne({}, {ssn: 1, salary: 1})
// Returns:
// {
//   "_id": ObjectId("..."),
//   "ssn": BinData(6, "AQAAAAAAAAAAAAAAAAAAAA..."),   // ciphertext — DBA cannot read
//   "salary": BinData(6, "AgAAAAAAAAAAAAAAAAAAAA..."), // ciphertext — DBA cannot read
//   "__safeContent__": [BinData(0, "..."), ...]        // range metadata — opaque
// }

KMS latency impact. Each distinct DEK used in a query session requires a KMS decrypt call. For a query that touches 3 QE-encrypted fields with 3 different DEKs, the driver makes 3 KMS API calls before sending the query. AWS KMS p99 latency is approximately 10–30ms per decrypt call. A query touching 3 DEKs adds 30–90ms of KMS overhead — acceptable for infrequent sensitive data lookups, problematic for high-frequency OLTP paths.

Mitigation: libmongocrypt caches decrypted DEKs in memory for the lifetime of the encrypted client instance. DEKs for frequently used fields are decrypted once and reused across queries in the same application process. Size the DEK cache (MongoClient is long-lived in application servers) and limit the number of distinct DEKs per collection to minimize cold-start KMS overhead.

Identifying QE metadata indexes. QE creates internal metadata indexes not visible via db.collection.getIndexes():

// QE creates two internal collections per encrypted collection:
// - <collection>.esc  — Equality State Collection (tracks encrypted equality entries)
// - <collection>.ecoc — Encrypted Compaction Output Collection (for compaction)
// These appear as regular collections but should never be manually modified

db.getCollectionNames().filter(n => n.includes('.esc') || n.includes('.ecoc'))
// Returns: ["employees.esc", "employees.ecoc"]

// After frequent inserts/updates, run compaction to prevent __safeContent__ bloat:
db.runCommand({compactStructuredEncryptionData: "employees"})

Where It Breaks

Failure ModeRoot CauseProduction Blast RadiusMitigation
Unsupported query type on QE field — regex, text, $existsApplication evolves to need a query type not declared at field creation (text search, regex, $elemMatch); these cannot be evaluated server-side against QE ciphertextQuery falls back to collection scan with application-layer decryption of every document — O(N) latency for any collection sizeMap all required query patterns per sensitive field before implementing QE; if open-ended query requirements are anticipated, use FLE v1 (decrypt before filter) or keep the field plaintext with application-layer access controls
KMS unavailability — application cannot queryThe KMS provider (AWS KMS, Azure Key Vault) is unreachable or rate-limited; libmongocrypt cannot decrypt DEKs; all QE-encrypted field operations failApplication cannot read or write QE-encrypted fields; non-QE fields continue to work normally; the encrypted fields degrade to inaccessibleImplement KMS DEK caching with appropriate TTL (1–4 hours); use KMS key replication across regions; test KMS failure scenarios explicitly in disaster recovery runbooks
__safeContent__ modification — silent query corruptionAn application or DBA script modifies the __safeContent__ array directly (e.g., during a data repair operation)Range queries return incorrect results without error; equality queries are unaffected (equality does not use __safeContent__)Implement field-level access controls on the __safeContent__ field in the MongoDB role definitions; add automated tests that verify query results match expected counts after any data maintenance operation
Range query bounds mismatch — documents outside declared rangeA salary range query field is declared with max: 500000; a document is inserted with salary 750000; the salary value falls outside the declared range treeThe document is inserted successfully but is never returned by range queries for values above 500000; no error is producedValidate all QE range field values against the declared min/max bounds at insert time in the application layer; set declared bounds 2–3× above the maximum expected value; treat bound changes as migrations requiring collection rebuild
DEK rotation — re-encryption not atomicThe security team rotates the DEK (creates a new DEK, re-encrypts all documents); during rotation, some documents are encrypted with old DEK, some with new DEK; if rotation fails midway, a mixed-key collection existsReads succeed but write operations with the new DEK fail for documents still encrypted with old DEK until rotation completes; if rotation is abandoned, the collection state is inconsistentUse MongoDB’s rewrapManyDataKey API for DEK rotation — it handles the re-encryption atomically per document; run rotation during low-traffic windows; verify rotation completion before switching application to the new DEK
Compaction neglect — __safeContent__ bloatQE’s range encryption scheme appends to __safeContent__ on each update to a range-encrypted field; without periodic compactStructuredEncryptionData commands, __safeContent__ arrays grow indefinitelyPer-document storage size grows with update count; collection storage expands beyond expected footprint; range query evaluation slows as server processes larger __safeContent__ arraysSchedule compactStructuredEncryptionData as a regular maintenance operation (weekly for high-update QE collections); monitor db.collection.stats().avgObjSize for unexpected growth
Audit log reveals query patternsMongoDB’s audit log records the encrypted query tokens sent to the server; a privileged auditor who can correlate repeated identical tokens can infer that the same plaintext value is being queried repeatedly — even without breaking the encryptionFrequency analysis on audit logs can reveal which encrypted values are most frequently queried; for equality-encrypted low-cardinality fields (gender, status), this reveals distribution informationUse QE equality encryption only on high-cardinality fields (SSN, account ID); for low-cardinality sensitive fields, consider application-layer tokenization (store a non-sensitive token, maintain the mapping in a separate secure store)
Production schema migration — adding QE to existing fieldA team adds QE encryption to an existing plaintext field in a running production collection; existing documents retain plaintext values while new documents receive ciphertextMixed collection: queries with QE configured only match documents with ciphertext (new documents); documents with plaintext values for the field are not returned by QE queriesThere is no in-place migration path for adding QE to an existing field; the collection must be rebuilt — read all documents in plaintext, insert into a new QE-configured collection; this is a planned migration, not an in-place ALTER

2025 MongoDB 8.0 Queryable Encryption Update

MongoDB 8.0 (GA October 2024) added trimFactor as a configurable parameter for range-encrypted fields — controlling the density of the bloom filter tokens stored in __safeContent__. A higher trimFactor (default 6) reduces the number of metadata tokens per document (smaller storage footprint, faster compaction) at the cost of reduced query precision (wider range scan on the metadata index). Lower trimFactor values increase metadata token density, narrowing range scans but increasing per-document storage overhead. For high-cardinality range fields (salary, date of birth, account balance), trimFactor: 4 reduces false positives in range evaluation; for lower-precision needs, trimFactor: 8 reduces storage overhead.

MongoDB 8.0 also introduced contentionFactor as a configurable parameter (previously fixed internally) — controlling how QE handles concurrent writes to the same field value. A higher contentionFactor reduces write contention at the cost of increased metadata entries per distinct value. For fields with high write concurrency on the same values (e.g., a status field with values shared across many documents), contentionFactor: 8 reduces lock contention at the QE metadata level.

The MongoDB Query API now includes $encryptedField as a hint in aggregation pipelines to explicitly route pipeline stages to client-side decryption when a pipeline expression cannot be evaluated server-side against QE ciphertext — replacing the previous behavior where unsupported pipeline stages silently fell back to full collection decryption without warning.

What to Do Next

  • Problem: MongoDB Queryable Encryption’s cryptographic scheme supports only equality and range query types for server-side evaluation; teams that implement QE without mapping all future query patterns per field discover the constraint as a schema migration requirement when a new feature requires text search or regex on an encrypted field — at which point the field must be re-encrypted in a new collection.
  • Solution: Map every anticipated query type for each sensitive field before implementing QE — equality-only fields use deterministic AEAD (same plaintext → same ciphertext); range fields require declaring min/max bounds and sparsity at creation time; any field requiring text search, regex, or complex aggregation cannot use QE and needs a different protection strategy.
  • Proof: MongoDB’s libmongocrypt source code (MIT licensed on GitHub) documents the structured encryption scheme used for QE — the server-side metadata index stores encrypted bloom filter tokens, not plaintext, confirming that the server evaluates queries by comparing encrypted tokens against the stored tokens without any decryption path on the server side.
  • Action: Audit your current schema for fields that contain PII, financial data, or health information and that are queried with equality or range predicates — these are the exact QE candidates; run the db.collection.stats() size check after enabling QE on a staging collection to measure the __safeContent__ storage overhead before committing to production.

Sources to Verify

  1. MongoDB Manual — Queryable Encryption Architecture and Supported Query Types: https://www.mongodb.com/docs/manual/core/queryable-encryption/
  2. MongoDB 8.0 Release Notes — Range Query Encryption Enhancements and trimFactor: https://www.mongodb.com/docs/manual/release-notes/8.0/
  3. MongoDB libmongocrypt Source Code — Structured Encryption Implementation: https://github.com/mongodb/libmongocrypt
  4. MongoDB Manual — ClientEncryption API Reference — createDataKey and encrypt: https://www.mongodb.com/docs/manual/reference/method/ClientEncryption/
  5. AWS KMS Latency and Throughput Limits — Service Quotas: https://docs.aws.amazon.com/kms/latest/developerguide/limits.html
  6. USENIX Security 2019 — Structured Encryption and its Applications: https://www.usenix.org/conference/usenixsecurity19/presentation/kamara
  7. MongoDB Manual — Compacting QE Collections — compactStructuredEncryptionData: https://www.mongodb.com/docs/manual/reference/command/compactStructuredEncryptionData/