MongoDB Tutorial 0/120 lessons ~6 min read Lesson 80

    Encryption

    Encryption protects data from being read by anyone without the key — even if they steal the disk, sniff the network, or dump a backup.

    Course progress0%
    Focus
    12 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    Encryption protects data from being read by anyone without the key — even if they steal the disk, sniff the network, or dump a backup. MongoDB supports three independent layers: encryption in transit (TLS), encryption at rest (storage engine), and client-side field-level encryption (CSFLE / Queryable Encryption) which keeps fields encrypted even from the DBA.

    Defense in depth means turning on all three — they protect against different threats and have very different operational costs.

    Learning objective: Apply Encryption correctly in a TechLearningPRO MongoDB workload — with clear data-model choices, safe writes, and failure modes you can explain in review.

    Treat every example as production-shaped MongoDB: explicit projections, indexes that match the access path, and Atlas-safe defaults. Prefer mongosh / Node driver shapes used in SaaS backends.

    Purpose of this lesson

    Apply Encryption correctly in a TechLearningPRO MongoDB workload — with clear data-model choices, safe writes, and failure modes you can explain in review.

    Understanding the topic

    The three layers — what each protects against:

    • TLS (in transit) — stops network sniffing and MITM. Mandatory on Atlas; one flag on self-hosted.
    • Encryption at rest — stops disk/backup theft. WiredTiger + KMIP/KMS-managed key (AWS KMS, Azure KV, GCP KMS).
    • CSFLE — fields encrypted in the driver before sending to the server. DBAs cannot read SSNs even with full cluster access.
    • Queryable Encryption (8.0+) — equality and range queries on encrypted fields without ever decrypting server-side.
    • Key hierarchy — CMK (in KMS) wraps DEKs (per field/collection) — rotating CMK is instant, no re-encryption.

    Step-by-step explanation

    1. State when Encryption is the right MongoDB tool versus an alternative.
    2. Map the diagram boxes to driver, mongod, WiredTiger, and your collection.
    3. Run the smallest correct mongosh / driver example against a TechLearningPRO learners collection.
    4. Name two failure modes (missing index, bad shard key, unbounded scan) and how you detect them.

    Informative example

    Client-side field-level encryption — Node driver:

    js
    const client = new MongoClient(uri, {
    autoEncryption: {
    keyVaultNamespace: "encryption.__keyVault",
    kmsProviders: { aws: { accessKeyId, secretAccessKey } },
    schemaMap: {
    "clinic.patients": {
    properties: {
    ssn: {
    encrypt: {
    keyId: [dataKeyId],
    bsonType: "string",
    algorithm: "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic" // queryable
    }
    }
    }
    }
    }
    }
    });
    // Insert — driver encrypts ssn transparently before sending
    await db.collection("patients").insertOne({ name: "Ada", ssn: "123-45-6789" });
    // Query by encrypted field — works because of Deterministic algorithm
    await db.collection("patients").findOne({ ssn: "123-45-6789" });

    Real-world use

    Banks store account numbers, PHI providers store diagnoses, and SaaS multi-tenant systems isolate tenant secrets all using CSFLE — the auditor sees only opaque binary blobs, and a rogue DBA cannot exfiltrate anything meaningful.

    Security implications

    MongoDB is a trust boundary. Drivers must not interpolate untrusted input into query operators.

    • Never build queries by concatenating user strings into operator objects.
    • Use least-privilege Atlas database users; apps should not have root.
    • Enable TLS and avoid exposing mongod on public networks.

    Best practices

    • TLS-only — set tlsAllowInvalidCertificates: false in production.
    • Store CMKs in a managed KMS, never on the application server.
    • Use Queryable Encryption for new projects on 8.0+ — better range support than legacy CSFLE.
    • Rotate DEKs after any insider incident; CMK rotation is cheap, do it yearly.

    Common mistakes

    • Encrypting everything — query patterns break and indexes become useless.
    • Storing the KMS key alongside the app secrets — same blast radius as no encryption.
    • Forgetting that backup snapshots are also encrypted — losing the key loses the data.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    3 questions
    1BeginnerQuestionWhat is Encryption and when do you use it?+

    Answer

    Three layers: TLS in transit, WiredTiger at rest, CSFLE for sensitive fields.
    2IntermediateQuestionHow would you verify Encryption is working in production?+

    Answer

    Queryable Encryption lets you search encrypted fields without decryption server-side.
    3AdvancedQuestionWhat breaks if you misuse Encryption?+

    Answer

    Managed KMS + key rotation = audit-grade compliance with minimal ops cost.

    Hands-on exercise

    Hands-on drill:

    • Implement the smallest correct example for Encryption on a learners/orders-like collection.
    • Capture explain('executionStats') and confirm an index was used when expected.

    Summary

    Encryption is a production MongoDB skill: model for your read path, prove it with explain(), and ship with indexes and least-privilege roles.

    Ready to mark this lesson complete?Track your journey across the entire course.