On this page
MongoDB Internals
How MongoDB actually stores, replicates, and serves documents underneath mongosh — the storage engine, the oplog, how an election really resolves, and the write-concern arithmetic that decides whether a failover loses data. For the operational side of running this on real VMs (firewall rules, mongod.conf, the Prometheus exporter, a step-by-step bootstrap), see on-prem-vm/mongodb.md; for the Kubernetes-operator version, see on-prem-k8s/mongodb.md.
WiredTiger Storage Engine
Every write goes through the same three structures, whether it's a single insertOne or a bulk load:
graph TD
classDef engine fill:#2c3e50,stroke:#1a252f,color:#fff
classDef mem fill:#3498db,stroke:#2471a3,color:#fff
classDef durable fill:#e67e22,stroke:#ba6018,color:#fff
classDef disk fill:#7f8c8d,stroke:#616a6b,color:#fff
CLIENT["MongoDB client"] -->|"insert / update / delete"| MONGOD["mongod process"]
MONGOD --> WT["WiredTiger Storage Engine"]:::engine
subgraph WT["WiredTiger"]
CACHE["WT Cache — in-memory B-tree pages<br/>size: wiredTigerCacheSizeGB<br/>default: 50% of (RAM − 1GB)"]:::mem
JOURNAL["Journal (WAL)<br/>append-only, fsynced every 100ms<br/>or immediately if j:true"]:::durable
CHECKPOINT["Checkpoint<br/>every 60s or 2GB of journal written<br/>flushes dirty cache pages to disk"]:::durable
end
CACHE -->|"dirty pages"| CHECKPOINT
CHECKPOINT --> DATA["Collection files (.wt)<br/>B-tree, snappy-compressed by default"]:::disk
CHECKPOINT --> IDX["Index files (.wt)<br/>B-tree on _id + user indexes"]:::disk
JOURNAL -.->|"replayed on crash recovery<br/>if newer than last checkpoint"| DATA
The journal and the checkpoint solve two different failure windows. A crash between checkpoints only loses what's replayable from the journal — that's why the journal is fsynced far more often (100ms) than a full checkpoint runs (60s). Without the journal, a crash mid-checkpoint could lose everything written since the previous checkpoint, not just the last 100ms.
mongod crashes 30 seconds after the last checkpoint, with the journal enabled. How much data is lost?
Sizing the cache
(RAM − 1GB) × 0.5, but on a real production host you also want headroom for per-connection memory (allocated outside the WiredTiger cache) and the OS page cache. 32 GB → cacheSizeGB: 12–14 is a safer starting point than the raw default.
db.serverStatus().wiredTiger.cache exposes "pages evicted because they exceeded the in-memory maximum" and "tracked dirty bytes in the cache." Rising eviction under normal load means the cache is undersized for the working set.
A host has 64 GB RAM. Someone sets cacheSizeGB: 60 to "maximize" MongoDB's cache. What breaks in production?
Document Model and BSON
MongoDB stores documents as BSON (Binary JSON), not JSON text:
BSON document: {_id: ObjectId("..."), name: "Alice", age: 30}
Binary encoding:
[doc_length 4B][type 1B][key "name\0"][value "Alice"][type 1B][key "age\0"][value 30 4B]...[terminator 0x00]
Why BSON, not JSON: the length-prefixed encoding means WiredTiger (and any driver) can skip over a field without parsing its contents — it just reads the 4-byte length and jumps. BSON also has native types JSON lacks: Date, ObjectId, Binary, Decimal128 — a JSON encoding would have to represent all of these as strings and lose type fidelity.
ObjectId is 12 bytes: 4-byte timestamp + 5-byte random value + 3-byte incrementing counter. That construction is deliberate — it's sortable by creation time, globally unique without a central sequence generator, and safe to generate on any node (including offline clients) without coordination.
Two documents are inserted from different application servers within the same second, with no shared database sequence. Why don't their ObjectIds collide?
Replication: Oplog, Elections & Quorum
The oplog
The oplog is a capped collection in the local database (local.oplog.rs). Every write on the primary is recorded as an idempotent operation — replaying the same oplog entry twice produces the same result, which is what makes replica catch-up and resync safe to retry.
sequenceDiagram
participant P as Primary — local.oplog.rs
participant S1 as Secondary 1
participant S2 as Secondary 2
Note over P: client write commits locally first
P->>P: append idempotent entry to oplog
par tailing cursor per secondary
S1->>P: tail oplog (long-lived cursor, not polling)
P-->>S1: stream new entries as they're appended
S1->>S1: apply entry, advance local optime
and
S2->>P: tail oplog (long-lived cursor)
P-->>S2: stream new entries
S2->>S2: apply entry, advance local optime
end
Note over S1,S2: each secondary's "optime" is how far it has replayed —<br/>this is exactly what rs.status() reports as replication lag
Op types: i (insert), u (update), d (delete), c (command — createCollection, dropCollection), n (no-op / keepalive, also used to fill in a stable point for chained replication).
Oplog window: capped at a fixed size — default 5% of disk space, minimum ~1 GB. If a secondary falls behind by more than the oplog window (its next needed entry has already rolled off), it can no longer catch up incrementally and must perform a full initial resync instead.
A secondary was network-partitioned for 6 hours. The primary's oplog only covers the last 4 hours of writes at current write volume. What happens when the secondary reconnects?
Elections and quorum
A replica set elects a primary by majority vote among voting members. An arbiter is a voting member that holds no data — it exists purely to break ties cheaply, without paying for a full extra data copy.
graph TD
classDef primary fill:#e74c3c,stroke:#c0392b,color:#fff
classDef secondary fill:#3498db,stroke:#2471a3,color:#fff
classDef arbiter fill:#f39c12,stroke:#ba6018,color:#fff
HB["Secondary misses primary heartbeat<br/>(default electionTimeoutMillis: 10s)"] --> NOM["Eligible secondary calls for election<br/>(nominates itself as candidate)"]
NOM --> VOTE["Every voting member casts one vote<br/>higher priority + more up-to-date optime wins ties"]
VOTE --> MAJ{"Candidate got<br/>a majority of votes?"}
MAJ -->|Yes| NEWP["Candidate becomes PRIMARY<br/>starts accepting writes"]:::primary
MAJ -->|No — split vote or<br/>no majority reachable| RETRY["Election fails, cluster stays without<br/>a primary; retried after a randomized backoff"]
subgraph "3-member set example"
P["Primary (1 vote)"]:::primary
S["Secondary (1 vote)"]:::secondary
A["Arbiter (1 vote, no data)"]:::arbiter
end
Why votes ≠ data copies: an arbiter's vote counts exactly the same as a data-bearing secondary's vote when computing whether a write reached w: "majority", or whether an election has a quorum — but it holds zero bytes of actual data. A 3-member Primary-Secondary-Arbiter (PSA) set only needs 2 of 3 votes to elect a new primary or acknowledge a majority write, and primary + arbiter alone satisfies that majority — even though the arbiter can never serve that data if the primary then dies.
In a PSA set, the secondary is temporarily unreachable. A write arrives at the primary with w: "majority". Does it succeed, and is it fully safe?
Try It Yourself: Live PSA Election
This is a different election model than the Raft demo elsewhere in this repo
(replication.md) — worth being precise about the
difference rather than treating "leader election" as one interchangeable
mechanic. Raft's demo picks whichever node happens to time out first and
wins purely on term number and majority; the first candidate to campaign
wins as long as its log qualifies. MongoDB's election is priority-weighted:
each member has a configured priority (default 1, arbiters always 0), a
member only calls an election after missing heartbeats for
electionTimeoutMillis (default 10s), and a higher-priority secondary that
is otherwise healthy can trigger its own election and take over from a
lower-priority primary even with no failure at all — a "priority takeover,"
not just a race to time out first. The demo below models that, plus the PSA
topology's specific risk: an arbiter votes but holds no data and can
never itself become primary.
Default topology is PSA: P1 (priority 1, data), S1 (priority 1, data,
starts as PRIMARY), A1 (arbiter — priority 0, no data). Click any node to
kill or revive it, use "Kill Primary" to force a failover, or add a
differently-prioritized secondary and watch it take over. Majority here is
computed against the full configured voting membership (not just currently
up nodes) — this is what makes the risk case below possible: kill the
arbiter, then kill either remaining data node, and the cluster has only 1
of 3 votes left and cannot elect anyone.
Rollback on rejoin
If the old primary had writes that were never replicated to any secondary before it crashed, and a new primary was elected and continued accepting new writes, the two oplogs have diverged. When the old primary rejoins as a secondary, MongoDB rolls back its un-replicated writes — moving them out to a rollback directory as BSON files rather than silently discarding them — so it can resync onto the new primary's oplog history.
After a rollback, where do the discarded writes actually go, and how would you recover one if it turned out to matter?
Write Concern and Read Concern — Deep Dive
Write concern controls how many replica set members must acknowledge a write before the client is told it succeeded. Getting this wrong is the single most common cause of "the failover ate my data."
sequenceDiagram
participant APP as Application
participant PRI as Primary
participant SEC as Secondary
Note over APP,SEC: writeConcern: {w: "majority", j: true}
APP->>PRI: insert document
PRI->>PRI: write to journal (j:true = fsync before ack)
PRI->>SEC: replicate via oplog tailing
SEC->>SEC: write to journal + apply
SEC-->>PRI: acknowledge
Note over PRI: majority (2/3 votes) confirmed
PRI-->>APP: write result: confirmed
Note over APP,SEC: readConcern: "majority"
APP->>PRI: find({_id: ...}) with majority read concern
PRI->>PRI: only return data already committed to a majority
Note over PRI: won't return data that could still be rolled back
PRI-->>APP: document (guaranteed stable, won't vanish on failover)
| Write concern | Data loss on failover | Latency |
|---|---|---|
{w: 0} |
Yes, silently | Lowest |
{w: 1} |
Yes, if only the primary had it | Low |
{w: "majority"} |
No | +1 replica round-trip |
{w: "majority", j: true} |
No, and disk-durable | Highest |
Why does pairing w: "majority" with j: true matter, when majority already implies more than one copy exists?
Aggregation Pipeline
An aggregation is a sequence of stages, each one transforming the document stream from the previous stage:
graph LR
COLL["orders collection"] --> MATCH["$match<br/>{status:'paid', created_at:{$gte:...}}"]
MATCH --> LOOKUP["$lookup<br/>join users by user_id"]
LOOKUP --> UNWIND["$unwind<br/>flatten joined array"]
UNWIND --> GROUP["$group<br/>{_id:'$user_id', total:{$sum:'$amount'}}"]
GROUP --> MATCH2["$match<br/>post-group filter: total >= 1000"]
MATCH2 --> SORT["$sort<br/>{total:-1}"]
SORT --> LIMIT["$limit: 100"]
LIMIT --> OUT["Result stream"]
db.orders.aggregate([
{$match: {status:"paid", created_at:{$gte: new Date("2024-01-01")}}}, // filter early, index-eligible
{$lookup: {from:"users", localField:"user_id", foreignField:"_id", as:"user"}},
{$unwind: "$user"},
{$group: {_id:"$user_id", total:{$sum:"$amount"}, count:{$sum:1}}},
{$match: {total:{$gte:1000}}}, // post-group filter, no index available here
{$sort: {total:-1}},
{$limit: 100},
{$project:{_id:0, user_id:"$_id", total:1, count:1}}
], {allowDiskUse: true}) // needed once an intermediate stage's working set exceeds 100MB RAM
explain('executionStats') on an aggregation shows exactly which stages used an index (IXSCAN) versus a full scan — the same distinction as a plain find().
Why can't the $match after $group in the pipeline above use an index, even though there's an index on total?
Index Types
// Standard B-tree
db.users.createIndex({email: 1}) // ascending
db.users.createIndex({email: 1, status: 1}) // compound
db.users.createIndex({email: 1}, {unique: true}) // unique
// Partial index — only indexes matching documents, smaller and faster
db.users.createIndex({email: 1}, {
partialFilterExpression: {deleted: {$exists: false}}
})
// TTL index — auto-deletes documents N seconds after createdAt
db.sessions.createIndex({createdAt: 1}, {expireAfterSeconds: 3600})
// Text index — full-text search
db.posts.createIndex({body: "text", title: "text"})
db.posts.find({$text: {$search: "kubernetes failover"}})
// Geospatial
db.locations.createIndex({coords: "2dsphere"})
db.locations.find({coords: {$near: {$geometry: {type:"Point", coordinates:[77.2,28.6]}, $maxDistance: 1000}}})
A TTL index is set with expireAfterSeconds: 3600 on a field called createdAt. A background job deletes stale sessions after exactly 60 minutes, right on the second. Is that guaranteed?
explain() — Query Analysis
// Find execution plan
db.orders.find({user_id: "123", status: "paid"}).explain("executionStats")
// winningPlan.stage: "COLLSCAN" = full scan (bad) | "IXSCAN" = index (good)
// executionStats.totalDocsExamined vs totalDocsReturned: large ratio = missing index
// Compound index matching the query shape
db.orders.createIndex({user_id: 1, status: 1})
// Covering index: every projected field is in the index itself — zero document fetches
db.orders.createIndex({user_id: 1, status: 1, amount: 1})
db.orders.find({user_id: "123"}, {status: 1, amount: 1, _id: 0})
// explain shows "Using index" — no heap/document reads at all
explain() shows totalDocsExamined: 50,000 and totalDocsReturned: 12 for a query that IS using an index (IXSCAN, not COLLSCAN). Is that fine?
Transactions (4.0+)
const session = db.getMongo().startSession();
session.startTransaction({ readConcern: {level: "snapshot"}, writeConcern: {w: "majority"} });
try {
const accounts = session.getDatabase("bank").accounts;
accounts.updateOne({_id: "alice"}, {$inc: {balance: -100}}, {session});
accounts.updateOne({_id: "bob"}, {$inc: {balance: 100}}, {session});
session.commitTransaction();
} catch (err) {
session.abortTransaction();
throw err;
} finally {
session.endSession();
}
readConcern: "snapshot" gives every read inside the transaction a consistent point-in-time view — as if the whole transaction ran instantaneously — even though the two updateOne calls execute sequentially.
The commitTransaction() call above uses writeConcern: {w: "majority"}. If the primary crashes between the two updateOne calls and before commitTransaction, what happens to Alice's already-decremented balance?
Change Streams
A real-time feed of insert/update/delete events, built directly on top of the oplog.
const stream = db.orders.watch([
{$match: {"operationType": {$in: ["insert", "update"]}}},
{$match: {"fullDocument.status": "paid"}}
]);
stream.on("change", change => processOrder(change.fullDocument));
// Crash recovery: persist the resumeToken, restart from exactly where you left off
const stream2 = db.orders.watch([], {resumeAfter: lastToken});
A change-stream consumer crashes and restarts 20 minutes later without a saved resumeToken. What happens to the events it missed?
Sharding
graph TD
classDef router fill:#8e44ad,stroke:#6c3483,color:#fff
classDef cfg fill:#f39c12,stroke:#ba6018,color:#fff
classDef shard fill:#2980b9,stroke:#1f618d,color:#fff
APP["Application"] --> MONGOS["mongos router<br/>stateless — no data of its own"]:::router
MONGOS -->|"chunk map lookup"| CFG["Config server replica set<br/>authoritative chunk-to-shard mapping"]:::cfg
MONGOS -->|"routes query to the<br/>right shard(s) only"| S1["Shard 1 replica set<br/>user_id: 0 – 500K"]:::shard
MONGOS --> S2["Shard 2 replica set<br/>user_id: 500K – 1M"]:::shard
CFG -.->|"balancer moves chunks<br/>to keep shards even"| S1
CFG -.-> S2
sh.enableSharding("mydb")
sh.shardCollection("mydb.orders", {user_id: "hashed"})
// hashed = even write distribution, but range queries scatter across every shard
// ranged = supports efficient range queries, but monotonically increasing keys hotspot one shard
sh.getBalancerState() // is the auto-balancer currently moving chunks?
Try It Yourself: Live Chunk Split & Migration
Pick a shard-key type, then insert values yourself. Try a monotonically increasing sequence (1, 2, 3, 4, …) under each mode and watch what happens to where the documents land — this is the same mechanism the toggle above describes and the quiz below tests, just running live instead of asserted in prose. Once one shard is visibly overloaded, click "Run balancer" and watch it split that shard's biggest chunk and migrate half of it to the least-loaded shard.
A collection is sharded on {createdAt: 1} (ranged) because "we need to query recent orders fast." Six months in, one shard is consistently at 90% disk while the others sit at 20%. Why?
Monitoring
db.currentOp({secs_running: {$gt: 5}}) // find long-running ops
db.killOp(opid)
db.setProfilingLevel(1, {slowms: 100}) // log queries slower than 100ms
db.system.profile.find().sort({ts: -1}).limit(10)
rs.status() // replica set health + per-member replication lag
Schema Validation
MongoDB's $jsonSchema validator runs on insert and update — like a DB constraint, not an ORM validation. Existing documents that don't match are not automatically rejected (controlled by validationLevel).
// Create collection with validation
db.createCollection("orders", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["user_id", "total", "status", "created_at"],
properties: {
user_id: {
bsonType: "objectId",
description: "must be an ObjectId"
},
total: {
bsonType: "decimal",
minimum: 0,
description: "must be non-negative decimal"
},
status: {
enum: ["pending", "paid", "shipped", "cancelled"],
description: "must be one of the allowed statuses"
},
created_at: {
bsonType: "date"
},
items: {
bsonType: "array",
minItems: 1,
items: {
bsonType: "object",
required: ["sku", "qty", "price"],
properties: {
sku: { bsonType: "string" },
qty: { bsonType: "int", minimum: 1 },
price: { bsonType: "decimal", minimum: 0 }
}
}
}
}
}
},
validationAction: "error", // "error": reject violating writes; "warn": log and allow
validationLevel: "strict" // "strict": validate all inserts+updates; "moderate": only docs that already match
})
// Add a validator to an existing collection
db.runCommand({
collMod: "orders",
validator: { $jsonSchema: { /* schema here */ } },
validationAction: "warn", // start with warn — see what would fail before enforcing
validationLevel: "strict"
})
// Inspect the current validator
db.getCollectionInfos({ name: "orders" })[0].options.validator
// Bypass validation (admin only — use for backfill migrations)
db.orders.insertOne({ /* doc */ }, { bypassDocumentValidation: true })
validationLevel semantics:
| Level | On insert | On update |
|---|---|---|
strict (default) |
Validates always | Validates always |
moderate |
Validates always | Only validates if the document currently matches the schema |
moderate is useful during migrations: existing non-conforming documents won't be rejected on update, giving you time to backfill them.
A collection has validationLevel="moderate" and validationAction="error". An existing document is missing a required field. A subsequent update to that document adds a new field. Is the update rejected?
Time Series Collections
Special collection type (MongoDB 5.0+) with bucketing built into the storage engine. MongoDB internally groups documents with the same metaField value into time-window buckets. Range scans and aggregations over time are significantly faster because they can skip entire buckets rather than scanning individual documents.
// Create a time series collection
db.createCollection("metrics", {
timeseries: {
timeField: "timestamp", // field containing the Date (required)
metaField: "host", // field identifying the series source (optional but important)
granularity: "seconds" // "seconds", "minutes", or "hours" — controls bucket window size
},
expireAfterSeconds: 2592000 // TTL: auto-delete buckets older than 30 days
})
// Insert — looks like a normal insert
db.metrics.insertMany([
{ host: "web-01", timestamp: new Date(), cpu_pct: 42.3, mem_pct: 71.0 },
{ host: "web-01", timestamp: new Date(), cpu_pct: 41.8, mem_pct: 70.5 },
{ host: "web-02", timestamp: new Date(), cpu_pct: 15.1, mem_pct: 55.2 }
])
// Efficient range query — hits only relevant buckets
db.metrics.find({
host: "web-01",
timestamp: {
$gte: new Date(Date.now() - 3600000), // last 1 hour
$lt: new Date()
}
})
// Aggregation over time — $dateTruncate for bucketed summaries
db.metrics.aggregate([
{ $match: { host: "web-01", timestamp: { $gte: new Date(Date.now() - 86400000) } } },
{ $group: {
_id: { $dateTruncate: { date: "$timestamp", unit: "minute", binSize: 5 } },
avg_cpu: { $avg: "$cpu_pct" },
max_mem: { $max: "$mem_pct" }
}},
{ $sort: { _id: 1 } }
])
Limitations vs regular collections:
- No ad-hoc updates to individual documents (update writes a new document; the old one is logically deleted inside its bucket)
- No unique indexes except compound
{metaField, timeField} timeFieldmust be a BSON Date — string timestamps require pre-processingmetaFieldis the primary cardinality axis — high-cardinality meta (e.g., per-request UUID) kills bucketing efficiency
A time series collection stores metrics with metaField="sensor_id". There are 10 million unique sensor IDs. Why does this kill bucketing efficiency?
Index Deep Dive: ESR Rule, Multikey, Wildcard
ESR Rule for Compound Index Field Order
The query planner's ability to use a compound index depends on field order. The ESR rule tells you the optimal order:
Equality fields first → Sort fields next → Range fields last
// Query: status = "active" AND created_at in last 7 days, sorted by score descending
db.users.find({
status: "active", // Equality
created_at: { $gte: sevenDaysAgo } // Range
}).sort({ score: -1 }) // Sort
// Bad index: {created_at, status, score}
// — range field first means sort and equality can't use the index efficiently
// Correct ESR index: {status, score, created_at}
db.users.createIndex({ status: 1, score: -1, created_at: 1 })
// Equality (status) → Sort (score) → Range (created_at)
Why: MongoDB walks the index left-to-right. Equality conditions narrow the index range precisely. Sort fields come next so MongoDB can satisfy the sort from the index without a blocking sort stage. Range fields come last because a range scan means the sort field values may not be contiguous in the remaining entries.
Multikey Indexes
An index on an array field is a multikey index — MongoDB creates one index entry per array element.
// Document: { tags: ["mongodb", "nosql", "database"] }
db.posts.createIndex({ tags: 1 }) // multikey — 3 index entries for this document
db.posts.find({ tags: "mongodb" }) // uses the multikey index
// Compound multikey restriction: at most ONE array field per compound index
db.posts.createIndex({ tags: 1, categories: 1 })
// ERROR: both are arrays → compound multikey with two array fields is forbidden
// Fix: index one array field and one scalar field
db.posts.createIndex({ tags: 1, author: 1 }) // OK: one array, one scalar
Wildcard Indexes
Index any field without knowing field names upfront — useful for user-defined schemas or document stores.
// Index all fields (use sparingly — large index size)
db.events.createIndex({ "$**": 1 })
// Index a specific nested path and its subfields
db.events.createIndex({ "properties.$**": 1 })
// Matches queries on properties.foo, properties.bar, properties.nested.deep
// Cannot be used for sort (wildcard indexes are query-only)
// Cannot be a unique index
A compound index is defined as {category: 1, tags: 1}. The "tags" field is an array. Is this index allowed? What about {tags: 1, categories: 1} where both fields are arrays?
$lookup Performance
$lookup is a server-side join. Without the right index, it does a collection scan of the from collection for every input document — O(N×M) cost.
// --- Equality join (simple form) ---
// REQUIRES an index on orders.user_id — verify before deploying
db.orders.createIndex({ user_id: 1 })
db.users.aggregate([
{ $match: { status: "active" } },
{
$lookup: {
from: "orders",
localField: "_id", // field from the "users" collection
foreignField: "user_id", // field from the "orders" collection — index this
as: "orders"
}
}
])
// --- Pipeline join (expressive form) ---
// Can apply conditions, projections, and computed fields inside the lookup
db.users.aggregate([
{
$lookup: {
from: "orders",
let: { uid: "$_id" }, // expose local field as a variable
pipeline: [
{ $match: {
$expr: { $eq: ["$user_id", "$$uid"] }, // use the variable
status: "paid" // additional filter inside lookup
}},
{ $project: { _id: 1, total: 1, created_at: 1 } }, // trim output
{ $sort: { created_at: -1 } },
{ $limit: 5 }
],
as: "recent_orders"
}
}
])
// Pipeline joins also require an index on the from collection's join field
// --- Check if the index is being used ---
db.users.aggregate([ /* pipeline */ ], { explain: "executionStats" })
// Look for: IXSCAN in the $lookup sub-pipeline (not COLLSCAN)
// "totalDocsExamined" inside $lookup sub-pipeline should equal returned docs
When to denormalize instead of $lookup:
- 1:1 relationships where the joined document is always needed together
- Joined documents are small and infrequently updated
- Query latency is critical (embedding eliminates the join entirely)
$lookup on sharded collections:
- The
fromcollection must be either unsharded or sharded by_id - Pipeline-form $lookup on sharded
fromtriggers scatter-gather — high latency on large shards
A $lookup joins users (10K docs) with orders (10M docs) on orders.user_id with no index on orders.user_id. How many total document examinations does MongoDB perform?
Aggregation Pipeline Optimization
The MongoDB query planner pushes some optimizations automatically. Others require manual stage ordering.
// 1. $match EARLY — eliminates documents before downstream stages process them
// Automatic: planner moves $match before adjacent $project
// Manual: always write $match before $lookup, $unwind, $group
db.orders.aggregate([
{ $match: { status: "paid", created_at: { $gte: thirtyDaysAgo } } }, // ← first
{ $lookup: { from: "users", localField: "user_id", foreignField: "_id", as: "user" } },
{ $unwind: "$user" },
{ $group: { _id: "$user.country", revenue: { $sum: "$total" } } }
])
// 2. $project EARLY — reduce document size before expensive stages
{ $project: { user_id: 1, total: 1, created_at: 1 } } // drop unused fields before $lookup
// 3. allowDiskUse — triggers when $sort or $group exceeds 100MB in-memory
db.orders.aggregate([ /* stages */ ], { allowDiskUse: true })
// Without it, a sort or group on a large dataset throws:
// "Exceeded memory limit for $group/$sort, but didn't opt in to external sorting"
// 4. explain a pipeline
db.orders.aggregate([
{ $match: { status: "paid" } },
{ $group: { _id: "$country", total: { $sum: "$amount" } } }
], { explain: "executionStats" })
// Look for: IXSCAN (not COLLSCAN) in the $match stage
// "nReturned" at each stage — large drops mean filtering is working
// "executionTimeMillisEstimate" — identifies the slow stage
// 5. Common anti-patterns
// BAD: $group before $match — aggregates the whole collection first
[
{ $group: { _id: "$country", total: { $sum: "$amount" } } },
{ $match: { total: { $gt: 1000 } } }
]
// GOOD: filter on indexed fields before $group
[
{ $match: { status: "paid" } },
{ $group: { _id: "$country", total: { $sum: "$amount" } } },
{ $match: { total: { $gt: 1000 } } }
]
// BAD: $unwind without prior $match — explodes every array element before filtering
[
{ $unwind: "$items" },
{ $match: { "items.sku": "ABC-123" } }
]
// GOOD: $match on array field before $unwind (uses multikey index on items.sku)
[
{ $match: { "items.sku": "ABC-123" } },
{ $unwind: "$items" },
{ $match: { "items.sku": "ABC-123" } } // second match after unwind is exact
]
An aggregation pipeline starts with $group followed by $match. The planner "optimizes" by moving $match before $group. Why is this optimization not always safe?
mongosh Admin Cookbook
Quick-reference one-liners for production administration.
// --- Current operations ---
// Find queries running longer than 5 seconds
db.currentOp({ "secs_running": { $gt: 5 }, "op": { $in: ["query", "command"] } })
// Columns to check: opid, client, ns, secs_running, planSummary
// Kill a specific operation
db.killOp(12345) // opid from currentOp output
// --- Query profiling ---
db.setProfilingLevel(1, { slowms: 50 }) // log queries > 50ms (0=off, 1=slow, 2=all)
db.system.profile.find({}, { op:1, ns:1, millis:1, ts:1, planSummary:1 }).sort({ts:-1}).limit(5)
db.getProfilingStatus() // check current threshold
// --- Index intelligence ---
// Find unused indexes (zero accesses since last restart — candidates for drop)
db.orders.aggregate([
{ $indexStats: {} },
{ $match: { "accesses.ops": 0 } },
{ $project: { name: 1, key: 1 } }
])
// Diagnose a slow query (look for COLLSCAN, totalDocsExamined >> nReturned)
db.orders.find({ user_id: ObjectId("..."), status: "paid" }).explain("executionStats")
// --- Replication ---
// Replication lag per member in seconds
rs.status().members.map(m => ({
name: m.name,
state: m.stateStr,
lagSecs: m.optimeDate ? (new Date() - m.optimeDate) / 1000 : null
}))
// Change sync source without restart
rs.syncFrom("10.0.0.1:27017")
// Check oplog window (must exceed backup + maintenance windows)
rs.printReplicationInfo()
// oplog size: 10240 MB
// log length: 24.3 hrs ← increase oplogSizeMB if this is too short
// --- Space reclamation ---
// Reclaim fragmented space after heavy deletes (blocks writes on the collection)
db.runCommand({ compact: "orders" })
// How much space is reclaimable:
db.orders.stats().wiredTiger["block-manager"]["file bytes available for reuse"]
// --- Connections ---
db.serverStatus().connections
// { current: 412, available: 51588, totalCreated: 29043 }
Backup & Point-in-Time Recovery
MongoDB's equivalent of XtraBackup is Percona Backup for MongoDB (PBM) — a physical hot backup tool that reads WiredTiger files directly and archives the oplog for PITR. mongodump is the logical alternative: simpler, no agent, no PITR.
mongodump vs Percona Backup for MongoDB (PBM)
# Logical BSON export
mongodump --uri="mongodb://user:pass@primary:27017" --out=/backup/dump/
# Restore:
mongorestore --uri="mongodb://user:pass@primary:27017" /backup/dump/
# No agent needed. Portable across major MongoDB versions.
# Downside: brief per-collection lock during export, no PITR.
</div>
<div class="tab-panel" data-tab-panel="pbm">
# Physical hot backup via PBM
pbm backup
# Reads WiredTiger .wt files directly — no locks on primary
# Backup runs on a secondary elected by PBM agents
# Oplog continuously archived for PITR
</div>
| mongodump | Percona Backup for MongoDB (PBM) | |
|---|---|---|
| Backup type | Logical (BSON) | Physical (WiredTiger files) |
| PITR | No | Yes (oplog-tail) |
| Restore time (1TB) | ~6 hours | ~30 minutes |
| Agent required | No | Yes (pbm-agent on each node) |
| Primary impact | Brief per-collection lock | Backup from secondary, zero primary impact |
| Cloud storage | Manual | S3/GCS native |
PBM Architecture
PBM runs a pbm-agent alongside every mongod. The agent elected for the backup reads WiredTiger files directly; all agents continuously tail the oplog for PITR archiving.
graph TD
PRI["Primary<br/>mongod"] -->|oplog stream| SEC1["Secondary 1<br/>mongod + pbm-agent"]
PRI -->|oplog stream| SEC2["Secondary 2<br/>mongod + pbm-agent"]
SEC1 -->|physical backup + oplog| S3["S3 / GCS<br/>backup storage"]
SEC2 -->|oplog tail| S3
CLI[pbm CLI] -->|commands via MongoDB| SEC1
CLI -->|commands via MongoDB| SEC2
Install & Configure PBM
# Install pbm-agent on every mongod node
apt install percona-backup-mongodb
# /etc/pbm-agent.env
PBM_MONGODB_URI="mongodb://pbmuser:password@localhost:27017/?authSource=admin"
systemctl enable --now pbm-agent
pbm-config.yaml (applied once via CLI):
storage:
type: s3
s3:
region: us-east-1
bucket: my-mongodb-backups
prefix: pbm/
credentials:
access-key-id: AKIA...
secret-access-key: ...
pitr:
enabled: true
oplogSpanMin: 10 # archive oplog slice every 10 min → RPO ≈ 10 min
pbm config --file pbm-config.yaml
pbm status # verify all nodes show pbm-agent as connected
Backup & PITR Restore
# Take a physical backup
pbm backup
# List available backups and PITR timeline
pbm list
# Restore to a specific point in time
pbm restore --time="2026-10-14T14:37:00"
# Restore a specific named full backup (no PITR)
pbm restore <backup-name>
Oplog Window Monitoring
PITR requires the oplog to continuously span from the base backup timestamp to the restore target. If the oplog wraps before PBM archives it, that window is lost.
// mongosh — check current oplog window
rs.printReplicationInfo()
// Output:
// oplog size: 10240 MB
// log length: 24.3 hrs ← must exceed backup interval + maintenance windows
// Set a guaranteed minimum retention in mongod.conf:
// storage.oplogMinRetentionHours: 48
// Rule: oplog window ≥ 2× your backup interval
You take a PBM physical backup at 02:00. The primary crashes at 09:00. PBM PITR is enabled with oplogSpanMin: 10. What is your RPO — how recent a restore target can you specify?
oplogSpanMin.mongodump runs for 3 hours on a 2TB cluster. A document is updated 5 times during the dump. Which version ends up in the backup?
--oplog to capture a consistent snapshot: mongodump records the starting oplog position and replays operations seen during the dump, producing a consistent view. For large clusters, use PBM instead.Search index not built yet — run npm run build first.