MongoDB DBA Associate cheat sheet
MongoDB DBA Associate · Keep the key ideas within reach.
Deployment, Installation, and Topology Planning
Replica set minimum for production high availability is three voting members; an arbiter provides a vote but no data and is unsuitable when the primary plus one data-bearing secondary cannot survive a failure.
A sharded cluster requires exactly these components: config server replica set (CSRS), one or more shard replica sets, mongos routers, and drivers connecting only to mongos.
Config servers must run as a replica set (CSRS) since MongoDB 3.4; legacy three-mirror (SCCC) config servers are unsupported in modern versions.
mongos is stateless and holds no persistent data; deploy at least two mongos instances and place them near application servers to avoid a single router as a failure point.
Bind IP defaults to 127.0.0.1; a node reachable by peers must set net.bindIp to the specific interface address or a comma-separated list, not 0.0.0.0 in hardened environments.
For a replica set, all members must share the same major/minor version family during rolling upgrades; the FCV (featureCompatibilityVersion) gates which features are active.
Election-related topology rule: an even number of voting members adds no fault tolerance over the next lower odd number; use arbiters or non-voting members to adjust votes without adding data-bearing nodes.
Read preference 'primaryPreferred' fails over reads to a secondary only when no primary is available; 'nearest' selects by measured latency among eligible members, not by geographic proximity alone.
Replica Set Configuration, Elections, and Failover
A majority is floor(votingMembers/2)+1; a primary must be able to see a majority to remain primary, otherwise it steps down.
Default election trigger: a member starts an election after electionTimeoutMillis (default 10000 ms) without hearing from the primary; heartbeats run every 2 seconds.
Priority 0 members can never become primary; hidden members must have priority 0 and are invisible to client read preference; delayed members apply an oplog delay via secondaryDelaySecs.
Votes are capped at 7; members beyond the seventh voting member must be configured with votes:0, and changing votes requires reconfig with the correct force option when a majority is unreachable.
w:majority write concern requires acknowledgment from a majority of data-bearing voting members; with w:1 a write can be rolled back if the primary fails before replication.
A rollback occurs when a node rejoins and has oplog entries the new primary never had; MongoDB writes the removed documents to rollback files for manual reconciliation.
rs.stepDown(seconds) forces the primary to relinquish; rs.freeze(seconds) prevents a member from seeking election; both are used to control failover timing during maintenance.
catchUpTakeoverDelayMillis (default 30000 ms) makes a higher-priority secondary wait for a better-positioned candidate before calling an election after a primary stepdown.
Sharding: Architecture, Shard Keys, and Balancer
Chunks default to 128 MB; the balancer migrates chunks, not documents, and migration rounds are triggered by chunk-count imbalance across shards.
Hashed shard keys give even write distribution but scatter reads for range queries; ranged keys support targeted range reads but risk hotspotting on monotonically increasing values.
A shard key is immutable on documents before MongoDB 5.0; from 5.0 onward documents can be moved between shards with updateOne using a full shard key in the filter.
Targeted queries include the full shard key; scatter-gather queries omit it and fan out to all shards, so shard key choice dominates query cost.
The balancer can be disabled with sh.stopBalancer() or per-window scheduling via sh.setBalancerState and the balancer window in the config database settings collection.
Zones associate shard key ranges with named shards; each zone must have at least one shard and each shard belongs to at most one zone; chunks need a matching zone range to migrate.
mongos caches routing metadata in the config database; stale routing after chunk migration is retried transparently, but long-running transactions can pin older metadata.
A unique index on a sharded collection must contain the shard key as a prefix; otherwise the index cannot be enforced cluster-wide.
Storage Engine, WiredTiger, and Data Modeling Considerations
WiredTiger uses document-level concurrency control; readers see a consistent snapshot without blocking writers, and writes are buffered and checkpointed every 60 seconds by default.
The journal (WiredTiger log) provides crash durability; writeConcern j:true forces journal acknowledgment, and j:false allows loss of writes since the last journal flush.
WiredTiger cache defaults to 50% of (RAM minus 1 GB) or 256 MB, whichever is larger; the cacheSizeGB setting caps this and eviction begins around 80% dirty or 95% total cache use.
The oplog is a capped collection in the local database; its size is set by replication.oplogSizeMB, and a too-small oplog causes secondaries to fall off and require full resync.
Embedding favors one-to-few and read-together data; referencing favors one-to-many with unbounded growth or independently accessed entities, avoiding the 16 MB document limit.
The 16 MB BSON document limit constrains array growth; the bucket pattern and outlier pattern split large logical entities across documents.
Schema validation uses $jsonSchema with validationLevel (strict/moderate) and validationAction (error/warn); collMod changes validation on an existing collection.
Index intersection is limited; compound indexes ordered by equality, sort, then range fields usually outperform relying on the planner to intersect single-field indexes.
Security: Authentication, Authorization, TLS, and Encryption
SCRAM-SHA-256 is the default authentication mechanism; internal member authentication uses keyfile or x.509, and enabling authorization without internal auth breaks replica set communication.
Built-in roles include read, readWrite, dbAdmin, clusterAdmin, userAdmin, root, and backup/restore; custom roles combine privileges with resource patterns such as {db:'app', collection:'*'}.
The localhost exception allows creating the first user only when no users exist and the node is accessed from localhost; it disappears after the first user is created.
TLS is enabled with net.tls.mode requireTLS plus certificateKeyFile; clients may present certificates for x.509 auth, and net.tls.allowConnectionsWithoutCertificates controls optional client certs.
Encryption at rest uses the WiredTiger encrypted storage engine with a key management provider: local keyfile for testing, KMIP or cloud KMS for production; the master key never resides in the data files.
Client-side field level encryption (CSFLE) encrypts specified fields before they reach the server; queryable encryption additionally permits equality or range queries on encrypted fields.
Auditing is an enterprise feature configured under auditLog with destination file, syslog, or console; the filter document selects which events are recorded.
Authentication restrictions: authenticationRestrictions on a user limits source IP ranges or CIDR blocks, and db.auth() in mongosh switches the authenticated user for the session.
Backup, Restore, and Disaster Recovery
mongodump captures BSON plus index definitions but not the oplog unless --oplog is used; restoring with --oplogReplay yields a point-in-time consistent snapshot only when the dump was taken with --oplog.
Filesystem snapshots require journaling enabled and a consistent state: either stop writes or use db.fsyncLock() before the snapshot and db.fsyncUnlock() after.
mongorestore --drop removes existing collections before restoring; without --drop, restored documents are merged into existing collections and can create duplicates.
A logical dump of a sharded cluster must go through mongos; per-shard dumps are inconsistent because chunk migrations may be in flight.
Point-in-time recovery combines a base backup with oplog replay to a timestamp; the oplog must extend back to the base backup time or recovery is impossible.
Restore testing is a control, not a formality: a backup is only valid once a restore into a separate environment has been verified against expected document counts and indexes.
For large datasets, physical backup (filesystem or Ops Manager/Cloud Manager snapshot) is faster than mongodump and preserves the exact on-disk format.
Recovery time objective drives topology: a three-member replica set tolerates one failure, and cross-region members protect against site loss at the cost of write latency under w:majority.
Monitoring, Diagnostics, and Performance Tuning
serverStatus exposes opcounters, connections, wiredTiger cache metrics, and globalLock queues; currentOp and $currentOp show in-flight operations, and killOp terminates a specific opid.
The database profiler levels are 0 (off), 1 (slow ops above slowms), and 2 (all ops); profiling writes to the system.profile capped collection and adds overhead.
explain('executionStats') reports totalKeysExamined, totalDocsExamined, and nReturned; a healthy index scan has totalDocsExamined close to nReturned.
A CO COLLSCAN stage in explain indicates a collection scan; IXSCAN with a high keys-to-docs ratio suggests a poorly selective index or a filter not covered by the index.
Replication lag is measured by comparing optimeDate of primary and secondary via rs.status(); a growing lag with a small oplog risks the secondary falling off and needing resync.
The slow query log threshold is set by operationProfiling.slowms or the slowms parameter; logLevel above 0 increases verbosity and should be temporary.
db.stats() and db.collection.stats() report storageSize, indexSize, and wiredTiger block-manager metrics used to size disks and detect index bloat.
mongotop reports per-collection read/write time and mongostat reports per-second opcounters, faults, and queue depths; both are point-in-time and best sampled over intervals.
Upgrades, Maintenance, and Operational Runbooks
Rolling upgrade order: upgrade secondaries one at a time, step down the primary so a secondary takes over, upgrade the former primary, then raise featureCompatibilityVersion last.
Never downgrade the FCV below the version required by stored data; setFCV to the previous version must precede any binary downgrade and only works within supported downgrade paths.
After a major upgrade, run the compatibility check: FCV stays at the old value until explicitly raised, so new features remain unavailable until setFeatureCompatibilityVersion runs.
Index builds on replica sets build on all members; on sharded clusters, unique index builds require a stop-the-world procedure or are coordinated by mongos depending on version.
Compaction reclaims disk space from WiredTiger fragmentation; it is run per-node with db.runCommand({compact:...}) and blocks that database's operations during execution.
Adding a member uses rs.add() or rs.addArb(); the new member performs an initial sync, and a large dataset may need maintenance windows or a seed from a filesystem snapshot.
Disk-full handling: WiredTiger stops accepting writes when the volume is full; monitor disk free space and keep the journal on the same volume sized for oplog plus data growth.
A runbook for a failed primary documents: detect via rs.status(), confirm majority, verify new primary optime, re-add the repaired node, and validate replication lag returns to baseline.
Tools and Automation: mongodump, mongorestore, mongosh, Ops Manager/Cloud Manager
mongodump --gzip --archive=backup.gz writes a single compressed archive; mongorestore --gzip --archive=backup.gz restores it, and --nsFrom/--nsTo rename namespaces during restore.
mongodump --oplog captures oplog entries during the dump for a consistent point-in-time restore with mongorestore --oplogReplay; it is unsupported for sharded clusters.
mongosh supports scripting with load(), EJSON for extended types, and --eval for one-liners; db.getSiblingDB() switches databases within a session.
mongosh connection strings accept SRV records (mongodb+srv://), authMechanism, and tls options; the shell respects readPreference for secondary reads.
Ops Manager and Cloud Manager provide automated backup with point-in-time restore, monitoring alerts, and rolling upgrade orchestration for self-managed deployments.
The Ops Manager agent (mongodb-mms-automation-agent) runs on each host and performs deployments and backups; the backup daemon stores snapshots in a blockstore or S3 bucket.
mongoexport and mongoimport handle JSON/CSV and are for data exchange, not backup; they lose BSON type fidelity and do not capture indexes.
mongostat and mongotop ship with the database tools and accept --rowcount and --discover to poll a URI for all members of a replica set or sharded cluster.