Install and secure MongoDB with authentication, TLS and backups
Deploy a three-member MongoDB Community Server 8.2 replica set on Ubuntu 24.04 with TLS/X.509 member identity, SCRAM least privilege, majority-aware clients and a full mongodump/oplog isolated restore drill.
Operate self-managed MongoDB with private authenticated transport, majority topology and recoverable logical backups while making version, FCV, scale, sharding and Queryable Encryption limitations explicit.
- MongoDB Community Server 8.2.11 or newer approved 8.2 patch
- MongoDB Database Tools 100.17.0
- Ubuntu Server 24.04 LTS, supported kernel excluding unresolved 6.19 incompatibility
- Topology Three data-bearing hosts in independent failure domains with stable private SAN-matching DNS and firewall paths.
- Version and kernel Official MongoDB 8.2.11+ approved patch, Database Tools 100.17.0 and currently supported Ubuntu kernel.
- PKI Unique CA-issued member certificates/keys with matching cluster identity attributes and tested rotation.
- Identity Secret manager, named admin/application/backup owners and role design; no argv/repository passwords.
- Capacity and SLO WiredTiger, oplog, initial sync, backup load, disk, memory, write concern and maintenance have representative tests.
- Recovery Encrypted independent repository and empty isolated same-major/FCV three-member restore target.
OneLiners never runs these steps or stores secrets. Review placeholders, versions, current state, and change-control requirements before using a command.
Full guide
What you will build
- A three-member self-managed MongoDB Community Server 8.2 replica set on Ubuntu 24.04 LTS, using the current stable 8.2 line and the latest approved patch (8.2.11 as of the guide verification date), with identical versions, private DNS identities and separate failure domains.
- TLS-required client and member communication using CA-issued certificates whose SANs match every advertised hostname and whose member identity attributes match the replica-set policy; no invalid-certificate or invalid-hostname bypasses.
- Authorization enabled with a localhost-exception bootstrap that immediately creates a named administrative user, application and backup users with narrow built-in or custom roles, protected interactive password handling, no credentials in URI/process list/history and audited role review.
- A WiredTiger and systemd configuration with private binding, explicit replica-set name, time synchronization, storage capacity, filesystem ownership, journaling, log rotation, resource limits, monitoring and an application connection string that lists all members with `replicaSet`, TLS and majority write concern.
- A verified backup program using MongoDB Database Tools 100.17.0 `mongodump --oplog` for a full replica-set logical dump, encrypted off-host retention, checksums and `mongorestore --oplogReplay` into an isolated compatible replica set, with explicit scale, consistency, sharding and Queryable Encryption limitations.
- All three members report MongoDB 8.2.11, one PRIMARY and two SECONDARY states, matching replica-set configuration, majority election capability, bounded lag, majority write concern behavior and clean TLS certificate validation.
- Unauthenticated, plaintext, invalid-CA, invalid-hostname and unauthorized database operations fail. Application and backup users perform only documented actions; the administrative identity is not embedded in applications or routine backup commands.
- A full logical dump includes oplog metadata, validates checksums and encrypted repository retention, restores into a same-major/FCV isolated replica set with oplog replay, and passes collection counts, indexes, validators, users/roles decision, representative document and application canary checks inside RPO/RTO.
Architecture
How the parts fit together
Three MongoDB Community Server 8.2 members run in separate failure domains with stable private DNS names. A standard production replica set uses an odd number of voting members; three data-bearing members provide majority election and two copies beyond the primary, while an arbiter does not store data and is not used as a shortcut here. Each `mongod` requires TLS and uses a CA-issued member certificate for internal X.509 membership; the certificate subject attributes used for cluster authentication must match across member certificates. Client users authenticate with SCRAM over TLS and receive least-privilege roles. Applications list all members, specify the replica-set name, validate TLS, use majority write concern where required and implement idempotent retry behavior. WiredTiger journals and replication provide local durability and availability, but operator deletion and corruption replicate, so backups live in a separate failure domain. `mongodump --oplog` creates a full logical BSON dump with an oplog slice for point-in-time restore on a replica set. It is suited to bounded datasets and migration/recovery workflows, not a universal low-impact backup system: it consumes read, CPU, memory, network and storage resources, requires same major version or feature compatibility on restore, does not support Queryable Encryption collections, and cannot combine oplog replay with namespace-limiting options. Sharded clusters require their dedicated documented procedure.
- Define data classification, topology, failure domains, read/write concern, RPO/RTO, backup scale, retention, encryption, restore validation and maintenance ownership.
- Install the latest approved MongoDB Community Server 8.2 patch and Database Tools 100.17.0 from official MongoDB repositories on three Ubuntu 24.04 hosts; pin only through a supported patch-management process.
- Install CA-issued member certificates and keys, verify SAN/subject/key usage/expiry and configure each member for private binding, requireTLS, X.509 cluster authentication, authorization and one replica-set name.
- Use the localhost exception only on the first isolated member to create the first administrative user, then enable the full secure configuration and never rely on the exception again.
- Initiate the replica set with stable DNS member hostnames, wait for PRIMARY/SECONDARY health, verify election majority, lag, TLS and application connectivity.
- Create application, monitoring and backup identities through interactive password prompts or protected config, grant minimum roles and run positive/negative authorization tests.
- Write a synthetic backup fixture, run a full `mongodump --oplog` against a suitable member under the backup identity, checksum and encrypt the completed directory off host.
- Restore with Database Tools 100.17.0 to an isolated MongoDB 8.2 replica set at matching FCV, use oplogReplay for the complete dump and validate database semantics.
- Operate patching, certificate/user rotation, replica maintenance, lag/oplog window, disk/cache, audit/slow query, backup age and recurring failover/restore exercises.
Assumptions
- MongoDB 8.2 is the current stable release for self-managed deployments as of 2026-07-28. MongoDB 8.2.11, released 2026-06-11 with security fixes, is the minimum exact reference; install a newer security patch in the 8.2 line when officially available and approved.
- MongoDB Database Tools 100.17.0 is the current tool line referenced by official mongodump/mongorestore documentation and is installed separately from MongoDB Server packages.
- Ubuntu Server 24.04 LTS hosts use a supported kernel. MongoDB 8.0 and newer has a documented incompatibility with Linux kernel 6.19 until MongoDB publishes a fixed build; the deployment verifies current official compatibility before rollout.
- Three data-bearing members use separate hosts and failure domains. All members normally run the same MongoDB major/minor version outside a documented rolling upgrade.
- Private DNS names are stable, resolve identically from every member/client and appear in TLS certificate SAN. Direct IP connection is avoided unless IP SAN is deliberately present.
- The organization has a CA and certificate lifecycle. Member certificates have matching required O/OU/DC attributes or configured extension value for internal authentication.
- A private firewall permits member-to-member TCP/27017 and approved client sources only. MongoDB is never exposed directly to the Internet.
- The localhost exception is available only before the first user/role exists and only from localhost. The bootstrap is performed before remote binding and is not a password-recovery mechanism.
- Applications support SCRAM credentials, TLS validation, replica-set discovery, majority write concern where required, retryable operations and bounded server-selection timeouts.
- Filesystem, memory, CPU and I/O capacity account for WiredTiger cache, indexes, journal, checkpoints, initial sync, backup reads and restore. Swap and transparent huge page policy follow current MongoDB production notes.
- The dataset is small/medium enough for logical `mongodump` within the backup window without unacceptable cache eviction or lag. Larger datasets use filesystem/cloud snapshots or MongoDB Ops Manager/Cloud Manager/Atlas continuous backup according to official guidance.
- A full replica-set `mongodump --oplog` is used for point-in-time logical backup. Namespace filters are not combined with oplog replay, and sharded clusters use the separate official sharded backup procedure.
- Queryable Encryption collections are absent from this mongodump workflow because mongorestore does not support them. The team inventories encrypted collections before backup selection.
- Backup passwords are prompted or stored in Database Tools `--config` files with restrictive permissions; credentials are never placed in connection strings printed by `ps`, shell history or logs.
Key concepts
- Replica set
- A group of mongod processes maintaining the same dataset. One primary accepts writes and secondaries replicate the oplog; elections require a voting majority.
- Write concern majority
- Acknowledges writes after a calculated majority of voting data-bearing members durably confirms them according to journaling semantics, reducing rollback exposure.
- Read concern
- Controls consistency/isolation guarantees for reads. `majority` returns data acknowledged by a majority and has latency/availability implications.
- Feature Compatibility Version
- Server setting controlling feature compatibility across upgrades. Restore tools require source and destination to use the same major version or same FCV.
- Localhost exception
- A bootstrap exception allowing creation of the first user/role from localhost only while no users/roles exist. It closes permanently once an identity is created.
- SCRAM
- Password-based challenge-response authentication used for MongoDB users. Password transport and server identity still require TLS.
- X.509 member authentication
- Internal replica-set members authenticate using CA-issued certificates whose configured identity attributes match.
- Oplog
- Capped local collection of replica-set operations. Its time window must exceed outages, backup and maintenance needs or initial sync may be required.
- mongodump --oplog
- Creates a complete logical dump and captures oplog entries occurring during the dump for point-in-time replay. It is valid only for a full replica-set dump.
- mongorestore --oplogReplay
- Restores a complete dump and replays the captured oplog slice. It cannot be combined with namespace selection, remapping or per-database/collection limiting options.
- Logical backup
- BSON documents and metadata exported through database APIs. It can be portable but consumes database resources and may not preserve every deployment-level setting.
- Application-consistent restore
- A restored dataset whose collections, indexes, validators, users/roles decision, transactions and dependent services satisfy application invariants, not only process startup.
Before you copy
Values used in this guide
{{mongoVersion}}Approved MongoDB Community Server 8.2 patch.
Example: 8.2.11{{toolsVersion}}Approved MongoDB Database Tools version.
Example: 100.17.0{{replicaSetName}}Stable replica-set name.
Example: rsOrders{{mongoOneHost}}First member private DNS name.
Example: mongo01.internal.example{{mongoTwoHost}}Second member private DNS name.
Example: mongo02.internal.example{{mongoThreeHost}}Third member private DNS name.
Example: mongo03.internal.example{{mongoPort}}Private TLS listener port.
Example: 27017{{mongoConfig}}mongod configuration path.
Example: /etc/mongod.conf{{mongoDataDir}}WiredTiger data directory.
Example: /var/lib/mongodb{{mongoLogPath}}MongoDB structured log file.
Example: /var/log/mongodb/mongod.log{{mongoTlsCert}}secretMember certificate and private key PEM.
Example: /etc/mongodb/tls/member.pem{{mongoTlsCa}}Trusted CA chain.
Example: /etc/mongodb/tls/ca.pem{{adminUser}}Named administrative SCRAM user.
Example: platform-admin{{appDatabase}}Application database.
Example: orders{{appUser}}Least-privilege application user.
Example: orders-api{{backupUser}}Backup identity with official required roles.
Example: backup-agent{{backupDirectory}}Root-only dump staging directory.
Example: /srv/mongodb-backup-stage/orders-20260728T020000Z{{restoreDirectory}}Isolated restore data path.
Example: /srv/mongodb-restore-drill{{restorePort}}Isolated loopback restore port.
Example: 27117{{expectedDigest}}SHA-256 manifest digest for completed dump.
Example: 47c1...full-reviewed-digestSecurity and production boundaries
- MongoDB is not exposed to the Internet. Private firewall, TLS and authentication are mandatory independent layers.
- Use official MongoDB packages and latest stable security patch. Record package repository, signing key fingerprint, version and kernel compatibility.
- TLS clients validate CA and hostname. Never use `tlsAllowInvalidCertificates` or `tlsAllowInvalidHostnames` in production.
- Member private keys and CA keys are credentials. Restrict member PEM to mongod and rotate certificates with a tested rolling procedure.
- The first admin password is entered interactively and never embedded in JavaScript files, URIs, argv, history or automation logs.
- Application users must not receive root, dbOwner, userAdminAnyDatabase or clusterAdmin. Grant only database actions required by tested code paths.
- Backup users need the official backup role and any necessary read/monitor permissions, not administrative user or role management.
- Database Tools warn that command-line passwords can be visible to `ps`. Omit the password for prompt or use a protected YAML config file.
- Connection strings contain usernames and topology even when password is omitted. Sanitize diagnostics and avoid embedding credentials.
- Backups contain entire documents, indexes and possibly user/role definitions depending on options. Encrypt, restrict, audit and expire them.
- Do not copy `/var/lib/mongodb` from a running process as an ad-hoc backup. Use coordinated snapshots or official backup tools.
- Majority write concern reduces rollback exposure but does not replace backup or application idempotency.
- Audit logs and slow query logs can contain namespaces, filters and values. Configure redaction/retention and restrict access.
- Avoid restoring users/roles blindly into an environment with different identity policy. Decide and test the authentication-database recovery procedure.
Stop before continuing if
- Stop if fewer than three data-bearing members or fewer than three independent failure domains are planned for production.
- Stop if active kernel is MongoDB-incompatible or package/version provenance is unknown.
- Stop if DNS names and certificate SAN/subject attributes do not match exactly.
- Stop if any member binds publicly or accepts non-TLS connections.
- Stop if localhost exception was consumed unexpectedly or no recoverable admin identity exists.
- Stop if application/backup user requires broad admin privileges or a password appears in argv/history/logs.
- Stop if members run different versions outside an approved rolling upgrade or FCV is unknown.
- Stop if replica set lacks majority, any member is unhealthy, lag exceeds objective or oplog window is too short.
- Stop if backup load causes SLO, cache, disk or replication-lag breach.
- Stop if mongodump uses namespace filters with `--oplog`, targets a sharded cluster without its documented procedure or includes Queryable Encryption collections.
- Stop if dump checksum/metadata is incomplete or off-host encryption/retention is unverified.
- Stop if restore destination version/FCV is incompatible or application semantic checks fail.
command
Verify host, kernel, DNS, capacity and package provenance
On all three Ubuntu hosts, confirm supported architecture/kernel, synchronized time, private DNS, storage and memory. Configure only the official MongoDB 8.2 repository and verify package candidates before installation.
Why this step matters
Package provenance, kernel support, DNS and time are prerequisites for reliable TLS, elections and storage. MongoDB 8.2.11 is the current stable patch reference as of verification. MongoDB documents an 8.0+ incompatibility with Linux kernel 6.19 until a fixed build is available, so kernel version is a release gate rather than incidental host metadata.
What to understand
Verify the official repository signing key fingerprint and HTTPS repository. Ubuntu's similarly named community packages are not the supported `mongodb-org` distribution.
Measure free RAM, filesystem type, IOPS, latency and space for WiredTiger data, journal, indexes, initial sync and backup reads. Use separate failure domains and stable DNS SAN names.
Time synchronization affects certificates, diagnostics and distributed behavior. Investigate offset; do not merely restart NTP during an unexplained incident.
System changes
- No service changes; reads host and package state.
Syntax explained
apt-cache policy- Shows candidate version and repository origin before installation.
NTPSynchronized- Reports whether systemd considers the clock synchronized.
Values stay on this page and are never sent or saved.
uname -a && timedatectl show --property=NTPSynchronized --value && getent hosts {{mongoOneHost}} {{mongoTwoHost}} {{mongoThreeHost}} && apt-cache policy mongodb-orgLinux mongo01 6.8.0-71-generic x86_64 GNU/Linux
yes
10.70.10.11 mongo01.internal.example
10.70.20.12 mongo02.internal.example
10.70.30.13 mongo03.internal.example
mongodb-org:
Candidate: 8.2.11
Version table:
*** 8.2.11 500
500 https://repo.mongodb.org/apt/ubuntu noble/mongodb-org/8.2 multiverse amd64 PackagesCheckpoint: Verify this layer before continuing
Continue whenAll three hosts use supported Ubuntu/kernel, resolve identical private member DNS, have synchronized time/capacity and offer official mongodb-org 8.2.11 or newer approved 8.2 patch.
Stop whenStop on kernel 6.19 incompatibility, wrong repository, DNS disagreement, public addressing, clock or capacity failure.
If this step fails
Candidate package is from Ubuntu rather than repo.mongodb.org.
Likely causeOfficial repository/key was not configured or a similarly named distribution package takes precedence.
apt-cache policy mongodb-org mongodbgrep -R 'repo.mongodb.org' /etc/apt/sources.list.d
ResolutionRemove unapproved repository selection, follow the official MongoDB Ubuntu installation steps and re-review the exact candidate.
Security notes
- Do not publish internal DNS, repository credentials or full host inventory. Repository signing keys are public; private automation credentials are not.
Alternatives
- Use an approved internal mirror that preserves official package signatures and provenance.
Stop conditions
- Stop on kernel 6.19 incompatibility, wrong repository, DNS disagreement, public addressing, clock or capacity failure.
command
Install the pinned MongoDB server, shell and Database Tools
Install the approved 8.2 patch consistently on every member and MongoDB Database Tools 100.17.0 on backup/restore hosts. Hold only under an owned security update process.
Why this step matters
All members should run the same major/minor/patch outside a controlled rolling upgrade. Database Tools version independently because they are not bundled with server packages. Recording both versions prevents restore failures being misattributed to data.
What to understand
Install the metapackage and exact component versions from one repository. Avoid mixing binaries copied from tarballs with package-owned systemd files.
A package hold can protect a coordinated rollout but also delay security fixes. Assign an expiry and monitor official security bulletins.
System changes
- Installs MongoDB binaries, service unit and tools but should not expose the service before secure configuration.
Syntax explained
mongodb-org={{mongoVersion}}- Requests the exact approved metapackage version.
mongodb-database-tools- Installs separately versioned mongodump and mongorestore utilities.
Values stay on this page and are never sent or saved.
sudo apt-get update && sudo apt-get install -y mongodb-org={{mongoVersion}} mongodb-org-server={{mongoVersion}} mongodb-org-shell={{mongoVersion}} mongodb-database-tools && mongod --version && mongosh --version && mongodump --versiondb version v8.2.11 Build Info: ubuntu2404 / x86_64 / OpenSSL 3.0.x 2.5.x mongodump version: 100.17.0 git version: <official-build-id> Go version: go1.24.x os: linux arch: amd64
Checkpoint: Verify this layer before continuing
Continue whenAll data nodes report the identical approved 8.2 patch and backup hosts report Database Tools 100.17.0.
Stop whenStop if apt starts an insecure default listener, versions differ, repository changes or tools are unsupported.
If this step fails
apt reports held broken packages or version not found.
Likely causeComponent versions differ, repository metadata is stale or architecture/distribution is unsupported.
apt-cache madison mongodb-orgdpkg -l 'mongodb-org*' 'mongodb-database-tools*'
ResolutionResolve all components to one approved release; do not force dependencies or partially upgrade a production replica set.
Security notes
- Package scripts run with privilege. Verify repository and pre/post-install behavior and keep service firewalled/stopped until configuration is ready.
Alternatives
- Build immutable images from official packages and promote a tested digest through environments.
Stop conditions
- Stop if apt starts an insecure default listener, versions differ, repository changes or tools are unsupported.
command
Install and validate member TLS identities
Install CA-issued member PEM and CA bundle on each host. Verify certificate/key match, SAN includes advertised member DNS plus localhost for the closed bootstrap, subject membership attributes match and expiry/rotation window is sufficient.
Why this step matters
TLS proves server identity to clients and member identity inside the replica set. MongoDB internal X.509 authentication compares configured certificate subject attributes, which must match across member certificates. SAN must match the hostname stored in replica-set configuration; a localhost SAN allows the initial loopback-only bootstrap without disabling hostname verification.
What to understand
The member PEM contains a private key and certificate chain. Restrict it to root/mongodb and inspect every parent directory. Never distribute the CA private key.
Test certificate rotation in staging and alert before expiry. Online certificate rotation is supported, but member and client compatibility must be planned.
Do not use one identical private key on every member. Each host receives a unique key/certificate with the shared membership attributes.
System changes
- Installs TLS certificate/private key and trust bundle on each host; mongod is not yet reconfigured.
Syntax explained
0640 root:mongodb- Allows mongod group read without exposing the member private key to other users.
SAN- Hostname identities clients validate; CN fallback is not a substitute for deliberate SAN.
Values stay on this page and are never sent or saved.
sudo install -d -o root -g mongodb -m 0750 /etc/mongodb/tls && sudo install -o root -g mongodb -m 0640 <member-pem> {{mongoTlsCert}} && sudo install -o root -g mongodb -m 0644 <ca-pem> {{mongoTlsCa}} && openssl x509 -in {{mongoTlsCert}} -noout -subject -issuer -dates -ext subjectAltNamesubject=O = Example Operations, OU = MongoDB Members, CN = mongo01.internal.example
issuer=O = Example Internal PKI, CN = Database Issuing CA
notBefore=Jul 20 00:00:00 2026 GMT
notAfter=Oct 20 00:00:00 2026 GMT
X509v3 Subject Alternative Name:
DNS:mongo01.internal.example, DNS:localhost
Certificate and private key: MATCH
Required O/OU member attributes: MATCH across 3 hostsCheckpoint: Verify this layer before continuing
Continue whenEvery host has unique matching key/cert, advertised member DNS plus localhost SAN, trusted chain, consistent membership attributes and safe permissions.
Stop whenStop on expired/unknown CA, hostname/subject mismatch, shared key, world-readable private key or untested rotation.
If this step fails
mongod reports The server certificate does not match the remote host name.
Likely causeReplica configuration advertises a DNS name missing from SAN or client uses an alias/IP.
openssl x509 -in {{mongoTlsCert}} -noout -ext subjectAltNamers.conf() host values
ResolutionReissue certificate or correct stable DNS/config under rolling procedure; never set allowInvalidHostnames.
Security notes
- Treat member PEM as both server and cluster credential. Rotate immediately after suspected disclosure.
Alternatives
- Use separate clusterFile and certificateKeyFile identities when organizational PKI policy requires distinct internal and client-facing certs.
Stop conditions
- Stop on expired/unknown CA, hostname/subject mismatch, shared key, world-readable private key or untested rotation.
config
Bootstrap one member on localhost with TLS
Before any user exists, configure mongo01 to listen only on loopback with TLS and the intended data/log paths. Start it isolated and use the localhost exception exactly once to create the first administrator.
Why this step matters
The localhost exception permits only the creation of the first user/role while none exist and access originates from localhost. Loopback-only TLS prevents a race where remote clients reach an uninitialized server. Once the first user exists, the exception closes permanently.
What to understand
Confirm the data directory is empty only for a new deployment. Never point bootstrap at unknown or prior production files.
Authorization can be enabled before bootstrap because the exception applies under its documented conditions. Use TLS even locally to verify certificate path early.
Do not add replica-set or remote bind until administrative identity and all member configuration are ready.
System changes
- Writes bootstrap mongod configuration and starts an isolated database process with empty data directory.
Syntax explained
bindIp: 127.0.0.1- Prevents remote access during the one-time identity bootstrap.
authorization: enabled- Requires authenticated users after the localhost exception is consumed.
{{mongoConfig}}Values stay on this page and are never sent or saved.
storage:
dbPath: {{mongoDataDir}}
journal:
enabled: true
systemLog:
destination: file
path: {{mongoLogPath}}
logAppend: true
logRotate: reopen
processManagement:
timeZoneInfo: /usr/share/zoneinfo
net:
port: {{mongoPort}}
bindIp: 127.0.0.1
tls:
mode: requireTLS
certificateKeyFile: {{mongoTlsCert}}
CAFile: {{mongoTlsCa}}
security:
authorization: enabledmongod bootstrap listener: 127.0.0.1:27017 TLS mode: requireTLS authorization: enabled users before bootstrap: 0 localhost exception: available public/private remote listener: none
Checkpoint: Verify this layer before continuing
Continue whenOnly loopback TLS listens, zero users exist before bootstrap and data/log paths plus journal are healthy.
Stop whenStop if any remote listener exists, data directory is non-empty/unowned or localhost exception status is uncertain.
If this step fails
Connection fails with certificate hostname mismatch on localhost.
Likely causeCertificate SAN lacks localhost while the bootstrap client connects to the loopback-only listener.
Use mongosh --host localhost and verify that the certificate contains DNS:localhost while the advertised member DNS remains present for final replica-set traffic.
ResolutionReissue the member certificate with the advertised member DNS and DNS:localhost, then retry; do not alter production DNS or disable certificate validation.
Security notes
- The bootstrap window is privileged. Restrict OS login and record the operator without capturing the password.
Alternatives
- Use X.509 administrative bootstrap if organizational identity lifecycle supports it.
Stop conditions
- Stop if any remote listener exists, data directory is non-empty/unowned or localhost exception status is uncertain.
command
Create the first administrator and close the exception
Connect locally over validated TLS and create a named administrator with an interactive password prompt inside mongosh. Do not place the password in a JavaScript file or shell argument. Disconnect and prove unauthenticated access is denied.
Why this step matters
The first identity becomes the recovery root for authorization. `passwordPrompt()` avoids literal password storage in history/source and sends it over TLS. The localhost exception closes after user creation, which must be verified before remote exposure.
What to understand
Use a high-entropy secret stored in the approved secret manager and a named human/admin workflow, not a shared application credential.
Root is justified only for break-glass platform administration. Routine database/user and monitoring tasks should use narrower roles and PIM/checkout.
Record the user name, authentication database and secret reference, never the password.
System changes
- Creates the first MongoDB user in admin and permanently consumes the localhost exception.
Syntax explained
passwordPrompt()- Prompts interactively so the secret is not typed as JavaScript source or shell argv.
db: admin- Stores the SCRAM user in the admin authentication database.
Values stay on this page and are never sent or saved.
mongosh --tls --host localhost --port {{mongoPort}} --tlsCAFile {{mongoTlsCa}}test> use admin
switched to db admin
admin> passwordPrompt()
Enter password: [hidden]
admin> db.createUser({user:"platform-admin",pwd:<prompt-result>,roles:[{role:"root",db:"admin"}]})
{ ok: 1 }
Unauthenticated db.runCommand({connectionStatus:1}):
MongoServerError: command connectionStatus requires authenticationCheckpoint: Verify this layer before continuing
Continue whenAdmin authenticates through TLS from approved path, unauthenticated commands fail and secret exists only in protected storage.
Stop whenStop if password appears in transcript, admin cannot reauthenticate or unauthenticated access remains.
If this step fails
createUser says there are already users.
Likely causeBootstrap data directory was reused or an earlier operator consumed the localhost exception.
Review protected deployment records and authenticate with the known existing administrator.
ResolutionStop and reconcile ownership; do not delete system.users or disable authorization to regain access.
Security notes
- Never paste admin credentials into URI, environment dump or `mongosh --password` command.
Alternatives
- Create separate scoped database administration users after bootstrap and keep root disabled/escrowed when not needed.
Stop conditions
- Stop if password appears in transcript, admin cannot reauthenticate or unauthenticated access remains.
config
Deploy the final TLS, X.509 and replica-set configuration
Apply the same configuration structure to all three members with each host's private bind address and unique member PEM. Enable authorization, X.509 cluster authentication and the stable replica-set name.
Why this step matters
The final configuration combines remote private reachability, mandatory TLS, client authorization and X.509 member authentication. Explicitly disabling localhost bypass removes ambiguity after bootstrap. Every member must share replica-set name and security policy while using its own private identity.
What to understand
Restart one new, non-initiated member at a time during initial build and test direct TLS/auth. For existing clusters, introducing TLS/X.509 needs the documented rolling transition rather than this new-deployment path.
Member certificate subject attributes must match. Bind only private addresses; firewall independently limits sources.
Config file must not contain SCRAM passwords. X.509 member private key is referenced by path and protected by filesystem permissions.
System changes
- Reconfigures/restarts mongod on each host to require TLS/auth and declare replica-set membership.
Syntax explained
clusterAuthMode: x509- Requires replica-set members to authenticate with trusted matching X.509 identities.
enableLocalhostAuthBypass: false- Explicitly disables localhost exception behavior.
{{mongoConfig}}Values stay on this page and are never sent or saved.
storage:
dbPath: {{mongoDataDir}}
journal:
enabled: true
systemLog:
destination: file
path: {{mongoLogPath}}
logAppend: true
logRotate: reopen
net:
port: {{mongoPort}}
bindIp: 127.0.0.1,<this-member-private-ip>
tls:
mode: requireTLS
certificateKeyFile: {{mongoTlsCert}}
CAFile: {{mongoTlsCa}}
security:
authorization: enabled
clusterAuthMode: x509
replication:
replSetName: {{replicaSetName}}
setParameter:
enableLocalhostAuthBypass: falseFinal configuration authorization: enabled localhost bypass: disabled TLS: requireTLS cluster authentication: x509 replica set: rsOrders bind: loopback + private member IP Internet listener: none Config parity digest: MATCH on 3/3 except host-specific bind/certificate
Checkpoint: Verify this layer before continuing
Continue whenEach member starts, validates admin TLS login, exposes only private/loopback, reports same replicaSetName and no unauthenticated/plaintext path.
Stop whenStop if any node cannot authenticate member/admin, uses public bind, differs in version/config or logs TLS identity errors.
If this step fails
mongod starts standalone despite replSetName in expected config.
Likely causeSystemd loads another configuration file or YAML indentation/path is wrong.
systemctl cat mongodps -ef | grep '[m]ongod'mongod --config {{mongoConfig}} --configExpand none
ResolutionStop service, correct the active unit/config source and verify exact command line before initiation.
Security notes
- Config and logs expose topology. Private key path permissions and journal access remain restricted.
Alternatives
- Use keyFile internal authentication only when X.509 member PKI is unavailable, with a high-entropy shared key protected/rotated separately.
Stop conditions
- Stop if any node cannot authenticate member/admin, uses public bind, differs in version/config or logs TLS identity errors.
command
Initiate the three-member replica set and verify majority
From authenticated mongo01, initiate a configuration using SAN-matching private DNS names and priorities. Wait for one PRIMARY and two SECONDARY members; do not add an arbiter as a substitute for a data-bearing member.
Why this step matters
A three-data-bearing-member set provides an odd voting majority and three copies. Stable DNS names are part of the replica-set identity returned to clients and must validate against TLS. Priority influences preference but cannot override health, freshness or majority.
What to understand
Wait for initial sync and SECONDARY state on both members. Compare versions, config version/term, optime and health.
Do not initiate multiple independent sets with the same name. Preserve config and logs if initiation partially succeeds.
Set application default write concern intentionally after testing. Majority requires healthy voting data-bearing members and can reduce availability during degradation.
System changes
- Creates the replica-set configuration and starts initial synchronization/election.
Syntax explained
_id: {{replicaSetName}}- Must exactly match `replication.replSetName` and client `replicaSet`.
priority- Influences primary preference; zero prevents a member from becoming primary.
Values stay on this page and are never sent or saved.
mongosh 'mongodb://{{adminUser}}@{{mongoOneHost}}:{{mongoPort}}/admin?tls=true&replicaSet={{replicaSetName}}' --tlsCAFile {{mongoTlsCa}} --passwordEnter password: [hidden]
rs.initiate({
_id: "rsOrders",
members: [
{_id:0,host:"mongo01.internal.example:27017",priority:2},
{_id:1,host:"mongo02.internal.example:27017",priority:1},
{_id:2,host:"mongo03.internal.example:27017",priority:1}
]
})
{ ok: 1 }
rs.status(): PRIMARY=1, SECONDARY=2, votingMembersCount=3, writableVotingMembersCount=3Checkpoint: Verify this layer before continuing
Continue whenOne PRIMARY and two SECONDARY members are healthy, same version, majority available, low lag and matching TLS identities.
Stop whenStop if no primary, unhealthy member, initial sync error, DNS/TLS mismatch, lag beyond objective or config has unexpected votes/priority.
If this step fails
rs.initiate returns AlreadyInitialized.
Likely causeThis data path already contains replica-set configuration or another operator initialized it.
rs.conf()rs.status()
ResolutionStop and reconcile the existing configuration; do not force reconfig or delete local database.
Security notes
- Replica-set reconfiguration is privileged and can affect election/data safety. Restrict admin access and audit changes.
Alternatives
- Use five members for additional failure-domain requirements after modeling election latency, cost and operational complexity.
Stop conditions
- Stop if no primary, unhealthy member, initial sync error, DNS/TLS mismatch, lag beyond objective or config has unexpected votes/priority.
command
Create least-privilege application and backup users
Authenticate as the administrator through a password prompt, create the application user in its authentication database with only required roles, and create a separate backup user in admin using the official backup role. Test negative permissions.
Why this step matters
Separating application and backup identities limits credential blast radius and attribution. `readWrite` is still broad within one database; production may need a custom role. The built-in backup role supplies operations required by mongodump without granting user administration or ordinary application writes.
What to understand
Create users through interactive passwordPrompt or a protected automation mechanism. Never put passwords in a checked-in JavaScript file.
Use separate users per application/environment and rotate through dual identities. Inspect inherited privileges with showPrivileges.
Run positive and negative operations through the actual driver because authentication database, retry and connection pooling can hide mistakes.
System changes
- Creates SCRAM credentials and role bindings replicated across the set; writes synthetic authorization test data.
Syntax explained
authSource database- User is stored/authenticated in the database where createUser runs unless URI specifies otherwise.
backup role- Built-in role intended for backup operations, not a general administrative account.
Values stay on this page and are never sent or saved.
mongosh 'mongodb://{{adminUser}}@{{mongoOneHost}}:{{mongoPort}}/admin?tls=true&replicaSet={{replicaSetName}}' --tlsCAFile {{mongoTlsCa}} --passwordEnter password: [hidden]
orders> db.createUser({user:"orders-api",pwd:passwordPrompt(),roles:[{role:"readWrite",db:"orders"}]})
{ ok: 1 }
admin> db.createUser({user:"backup-agent",pwd:passwordPrompt(),roles:[{role:"backup",db:"admin"}]})
{ ok: 1 }
orders-api insert into orders: PASS
orders-api read admin.system.users: DENIED
orders-api createUser: DENIED
backup-agent write orders: DENIEDCheckpoint: Verify this layer before continuing
Continue whenApplication and backup positive paths pass; cross-database, user admin, role admin and application writes by backup user fail.
Stop whenStop if broad admin role is needed, password leaks, or any forbidden operation succeeds.
If this step fails
User authenticates only when authSource=admin.
Likely causeThe user was created in admin rather than {{appDatabase}}, or client URI defaults to the target database incorrectly.
db.getUser('{{appUser}}', {showPrivileges:true}) in expected database
ResolutionCorrect the protected connection configuration or recreate user in the intended authentication database under change control.
Security notes
- Database credentials and SCRAM material are sensitive. Restrict system.users backups and admin outputs.
Alternatives
- Use custom roles with exact collection actions when readWrite exceeds required privilege.
Stop conditions
- Stop if broad admin role is needed, password leaks, or any forbidden operation succeeds.
verification
Validate client topology, TLS and majority semantics
Connect with all three member seeds, exact replica-set name, TLS CA and interactive application password. Verify primary discovery, server selection, majority write concern, unauthorized failures, index/validator baseline and bounded retry behavior.
Why this step matters
A direct connection to one node can appear healthy while replica discovery, certificate names or write concern are broken. Multi-seed URI and replicaSet make the driver discover the topology. Majority writes reduce rollback exposure but can time out when majority is unavailable; application behavior must distinguish unknown commit result from definite failure.
What to understand
Test one planned primary stepdown separately, with idempotent synthetic transactions and monitoring. Retryable writes do not make arbitrary application workflows idempotent.
Verify read preference and read concern explicitly. Secondary reads may be stale; majority reads have different guarantees and availability.
Inspect indexes and validators before load. Authorization does not prevent an application from issuing expensive allowed queries.
System changes
- Creates a synthetic majority-acknowledged fixture and may exercise client pool/server selection.
Syntax explained
replicaSet={{replicaSetName}}- Requires driver to discover and use the named replica set rather than a standalone endpoint.
w=majority&wtimeoutMS=5000- Requests majority acknowledgement with a bounded wait; timeout can leave commit outcome uncertain.
Values stay on this page and are never sent or saved.
mongosh 'mongodb://{{appUser}}@{{mongoOneHost}}:{{mongoPort}},{{mongoTwoHost}}:{{mongoPort}},{{mongoThreeHost}}:{{mongoPort}}/{{appDatabase}}?replicaSet={{replicaSetName}}&tls=true&w=majority&wtimeoutMS=5000' --tlsCAFile {{mongoTlsCa}} --passwordEnter password: [hidden]
Topology type: ReplicaSetWithPrimary
Primary: mongo01.internal.example:27017
Secondaries: mongo02.internal.example:27017, mongo03.internal.example:27017
Write concern: { w: "majority", wtimeout: 5000 }
Synthetic transaction: committed
Unauthorized admin read: denied
TLS validation: passed for 3/3 member hostnamesCheckpoint: Verify this layer before continuing
Continue whenDriver validates all hosts, discovers one primary/two secondaries, majority fixture commits, negative authorization and retry tests behave as designed.
Stop whenStop if directConnection is required, hostname validation is bypassed, majority times out or authorization leaks.
If this step fails
Server selection times out after one member is unavailable.
Likely causeClient has one seed, wrong replicaSet, DNS/TLS mismatch or remaining members cannot form majority.
rs.status()Inspect sanitized driver topology errors
ResolutionCorrect multiple seeds/name/TLS and majority health; do not switch to directConnection in production.
Security notes
- Do not put password in URI shown by ps/logs. Use driver secret provider and redact connection monitoring.
Alternatives
- Use SRV records only with controlled DNS and TLS name design; still test seed and topology failure behavior.
Stop conditions
- Stop if directConnection is required, hostname validation is bypassed, majority times out or authorization leaks.
command
Create and verify a full logical dump with oplog
Select a healthy member under the backup design, create a full replica-set dump with `--oplog` and gzip using Database Tools 100.17.0. Prompt for password or use a protected config file; do not apply namespace filters.
Why this step matters
A full `mongodump --oplog` captures logical BSON plus operations that occur during the dump, enabling a point-in-time replay. The option requires a replica set and a complete dump; namespace limiting conflicts with oplog replay. The dump is not impact-free and must be monitored for cache eviction, lag and SLO.
What to understand
Database Tools can read from the selected topology, but backup read preference and hidden secondary design require explicit testing. A lagging secondary can affect recovery point.
Do not use this procedure for a sharded cluster; follow the official self-managed sharded cluster dump procedure. Do not use it for Queryable Encryption collections.
After completion, create a deterministic manifest of every file, size and digest, encrypt/upload off host, record repository version/retention and remove local staging.
System changes
- Reads the full logical dataset/oplog and creates a sensitive compressed backup directory, consuming database and host resources.
Syntax explained
--oplog- Captures an oplog slice during a full replica-set dump for point-in-time replay.
omit --password- Prompts interactively because a username is supplied without a password, keeping the secret out of process arguments.
--gzip- Compresses individual BSON and metadata dump files; does not encrypt them.
Values stay on this page and are never sent or saved.
mongodump --host '{{replicaSetName}}/{{mongoOneHost}}:{{mongoPort}},{{mongoTwoHost}}:{{mongoPort}},{{mongoThreeHost}}:{{mongoPort}}' --username {{backupUser}} --authenticationDatabase admin --tls --tlsCAFile {{mongoTlsCa}} --oplog --gzip --out {{backupDirectory}}Enter password: [hidden] writing admin.system.users to /srv/mongodb-backup-stage/.../admin/system.users.bson.gz writing orders.orders to /srv/mongodb-backup-stage/.../orders/orders.bson.gz done dumping orders.orders (125000 documents) writing captured oplog to /srv/mongodb-backup-stage/.../oplog.bson dump completed: 0 errors Database Tools: 100.17.0 Manifest SHA-256: 47c1a5...
Checkpoint: Verify this layer before continuing
Continue whenFull dump completes with zero errors, root oplog exists, file manifest/digest is stable, repository copy is encrypted/retained and cluster SLO remains healthy.
Stop whenStop on namespace filters, sharded/queryable-encrypted topology, lag/SLO breach, missing oplog, tool/version mismatch or repository failure.
If this step fails
mongodump errors that --oplog cannot be used with --db.
Likely causeThe command limits namespaces, which is incompatible with full oplog point-in-time semantics.
mongodump --helpReview sanitized command options
ResolutionRemove namespace filters and perform a full replica-set dump, or omit oplog and explicitly document weaker per-namespace consistency.
Security notes
- Dump contains full documents and possibly identity data. Gzip is not encryption; enforce repository encryption and least privilege.
Alternatives
- Use coordinated filesystem/cloud snapshots or Ops Manager continuous backup when logical dump impact/scale fails objectives.
Stop conditions
- Stop on namespace filters, sharded/queryable-encrypted topology, lag/SLO breach, missing oplog, tool/version mismatch or repository failure.
command
Restore with oplog replay into an isolated compatible replica set
Provision an empty loopback-only MongoDB 8.2 replica set at matching FCV with authorization temporarily disabled, validate the dump manifest and use Database Tools 100.17.0 `mongorestore --oplogReplay`. This avoids the documented `--drop` failure mode in which restoring `admin` replaces the only destination credential mid-run. Enable authorization immediately after restore and verify the restored source administrator before any listener is exposed.
Why this step matters
Restore is the evidence that a dump is usable. Matching server major version or FCV and Database Tools avoids unsupported translation. An empty quarantined target makes `--drop` safe for the drill; the same flag against an existing deployment is destructive. Because the complete dump includes the `admin` database, restoring with authorization enabled can replace the authenticated user during `--drop` and leave an empty database. The drill therefore uses a loopback-only, authorization-disabled destination, restores the complete identity state, then enables authorization before any network exposure. Oplog replay completes the point-in-time full dump.
What to understand
Verify destination identity, emptiness, loopback-only binding and isolation immediately before command. Use a distinct restore replica-set name and firewall namespace so production clients cannot discover it.
Compare databases/collections, counts, representative BSON type/value digests, indexes, TTL indexes, validators, views and application invariants. Decide whether users/roles are restored or recreated from identity-as-code.
After restore, stop the listener, enable authorization in the reviewed configuration, restart still on loopback, and prove the restored administrator authenticates. If identity-as-code is authoritative, reconcile only after preserving the recovered dump and before widening access.
Measure source dump start/end, oplog replay point, restore duration and application validation. A process exit code is not application acceptance.
After evidence capture, stop the isolated listeners, remove any drill-only identities introduced during validation and securely remove restored data under policy.
System changes
- Drops/recreates collections only in the isolated restore set, writes all dump data and replays oplog; this is destructive to destination contents.
Syntax explained
--oplogReplay- Replays root oplog.bson after the complete restore and cannot be combined with namespace limiting/remapping.
--drop- Drops each destination collection before restore; safe only after proving the destination is disposable and isolated.
Values stay on this page and are never sent or saved.
mongorestore --host '{{replicaSetName}}-restore/127.0.0.1:{{restorePort}}' --tls --tlsCAFile <restore-ca> --gzip --oplogReplay --drop {{backupDirectory}}preparing collections to restore from restoring orders.orders from orders/orders.bson.gz 125000 document(s) restored successfully. 0 document(s) failed to restore. restoring indexes for collection orders.orders replaying oplog oplog replay completed Validation: collections: MATCH documents: MATCH indexes: MATCH validators: MATCH representative digests: MATCH application canary: PASS RPO: 00:01:18 RTO: 00:24:39
Checkpoint: Verify this layer before continuing
Continue whenExact manifest restores on matching 8.2/FCV, oplog replay succeeds, authorization is re-enabled on loopback, the restored administrator and metadata/application checks pass, RPO/RTO are recorded and cleanup is complete.
Stop whenStop on a remotely reachable or non-empty destination, authorization unexpectedly enabled during the full admin restore, version/FCV mismatch, restore error, missing metadata/oplog, semantic mismatch or credential leak.
If this step fails
mongorestore says not authorized to replay oplog.
Likely causeThe supposedly isolated destination still has authorization enabled, the command reached the wrong deployment, or the full restore procedure was changed to use an insufficient identity.
Confirm destination identity, loopback bind, authorization setting and documented mongorestore access without printing secrets.
ResolutionDo not grant broader rights on an unknown destination. Recreate the disposable loopback-only target from its reviewed baseline, keep authorization disabled only for the restore window, repeat the restore, then enable authorization before validation.
Security notes
- `--drop` is destructive. Require typed destination confirmation/change approval and never store passwords in argv.
Alternatives
- Restore without users/roles and recreate identities from reviewed code when destination security policy differs.
Stop conditions
- Stop on a remotely reachable or non-empty destination, authorization unexpectedly enabled during the full admin restore, version/FCV mismatch, restore error, missing metadata/oplog, semantic mismatch or credential leak.
Finish line
Verification checklist
mongosh '<sanitized-replica-set-uri>' --tlsCAFile {{mongoTlsCa}} --password --eval 'rs.status()'All three members run approved 8.2 patch with one PRIMARY, two SECONDARY and majority health.openssl s_client -connect {{mongoOneHost}}:{{mongoPort}} -servername {{mongoOneHost}} -CAfile {{mongoTlsCa}} </dev/nullEvery member certificate chain/hostname validates; plaintext, invalid CA and unauthenticated clients fail.mongosh '<application-uri>' --tlsCAFile {{mongoTlsCa}} --passwordApplication and backup positive actions pass; cross-database, role/user administration and backup writes fail.find {{backupDirectory}} -type f -print0 | sort -z | xargs -0 sha256sumFull dump, metadata and oplog files match recorded manifest and encrypted repository retention.mongosh '<restore-uri>' --tlsCAFile <restore-ca> --password --eval 'db.adminCommand({listDatabases:1})'Matching 8.2/FCV restore replays oplog and passes collection, document, index, validator, user/role decision and application checks within RPO/RTO.Recovery guidance
Common problems and safe checks
apt cannot find mongodb-org 8.2 packages.
Likely causeOfficial repository, architecture, distribution codename or signing key configuration is wrong.
apt-cache policy mongodb-orggrep -R 'repo.mongodb.org' /etc/apt/sources.list.d
ResolutionUse the official MongoDB Ubuntu 24.04 repository instructions and verified key; do not install Ubuntu's unrelated mongodb package.
mongod crashes on startup with Linux kernel 6.19.
Likely causeMongoDB 8.0+ documented TCMalloc incompatibility with kernel 6.19 applies to the installed patch.
uname -rmongod --versionjournalctl -u mongod -n 100
ResolutionStop and use a MongoDB-supported kernel or officially fixed MongoDB build after checking current release notes.
mongod fails to read member PEM.
Likely causeOwnership, mode, parent traversal, PEM key mismatch, passphrase or mandatory access control blocks it.
namei -l {{mongoTlsCert}}openssl x509 -in {{mongoTlsCert}} -noout -subject -issuer -dates
ResolutionCorrect narrow mongod-readable permissions and valid PEM; never make the private key world-readable.
TLS client reports hostname mismatch.
Likely causeClient hostname is absent from SAN or replica config advertises another name.
openssl x509 -in {{mongoTlsCert}} -noout -ext subjectAltNamegetent hosts {{mongoOneHost}}
ResolutionIssue correct certificates and use stable SAN-matching DNS names; never bypass hostname validation.
Replica members reject each other's X.509 certificate.
Likely causeRequired O/OU/DC attributes or configured clusterAuthX509 extension differ.
openssl x509 -in {{mongoTlsCert}} -noout -subject
ResolutionReissue member certs under one approved identity policy and roll them safely before initiating/rejoining.
Localhost exception no longer allows createUser.
Likely causeA user or role already exists, so the one-time exception closed.
Review bootstrap logs and prior user creation evidence.
ResolutionAuthenticate with an existing admin or use the documented recovery process; do not delete user collections or disable authorization.
rs.initiate cannot reach another member.
Likely causeDNS, firewall, TLS, certificate, bindIp or replica-set name is inconsistent.
mongosh TLS connection to each hostgetent hosts member namesjournalctl -u mongod
ResolutionFix member-to-member reachability and identity on every host before retrying configuration.
Replica set has no PRIMARY.
Likely causeNo voting majority, clock/network issue, configuration mismatch or all eligible members are unhealthy.
rs.status()rs.conf()db.serverStatus().repl
ResolutionRestore majority communication and healthy members; do not force reconfig unless the documented disaster procedure applies.
A SECONDARY remains STARTUP2 or RECOVERING.
Likely causeInitial sync, disk, index build, oplog window, data corruption or resource exhaustion blocks transition.
rs.status()rs.printSecondaryReplicationInfo()member logs
ResolutionResolve capacity/network errors, preserve evidence and rebuild via initial sync only after confirming another good majority copy.
Replication lag grows during backup.
Likely causemongodump read pressure evicts cache or saturates CPU, disk/network and secondary apply.
rs.printSecondaryReplicationInfo()mongostatiostat -xz 1 5
ResolutionStop/limit backup, choose a suitable secondary, reschedule or adopt snapshot/continuous backup for the dataset scale.
Application receives AuthenticationFailed.
Likely causeWrong authSource, username/password, SCRAM mechanism, secret rotation state or TLS endpoint.
Inspect sanitized URI fields and user database/roles as admin.
ResolutionCorrect protected secret and `authSource`; use dual-user rotation and never paste password into a diagnostic command.
Application can modify another database.
Likely causeUser has broad role, inherited custom role or authenticates as admin.
db.getUser('{{appUser}}', {showPrivileges:true})connectionStatus
ResolutionRevoke broad roles, bind only required application database permissions and repeat negative tests.
Majority writes time out.
Likely causeFewer than majority data-bearing voters acknowledge due to lag, disk, network or write concern timeout.
rs.status()rs.printSecondaryReplicationInfo()serverStatus
ResolutionRestore replica health and capacity; do not lower write concern without explicit data-loss approval.
Oplog window is shorter than maintenance/backup needs.
Likely causeWrite rate increased or oplog size is insufficient.
rs.printReplicationInfo()rs.printSecondaryReplicationInfo()
ResolutionResize oplog through documented command after capacity review and test initial-sync/recovery assumptions.
mongodump --oplog says option is unsupported.
Likely causeCommand uses --db, --collection, nsInclude/nsExclude or targets standalone/mongos incorrectly.
mongodump --helpReview sanitized command and topology.
ResolutionRun a full replica-set-member dump with --oplog or choose a separate non-PIT namespace backup without claiming oplog consistency.
mongodump fails on Queryable Encryption collection.
Likely causeDatabase Tools do not support the encrypted collection behavior.
Inventory encryptedFields collection options.
ResolutionUse the officially supported Queryable Encryption backup/migration path; do not omit affected collections silently.
mongodump completes but dump is much smaller than expected.
Likely causeWrong URI/database, authorization omitted namespaces, filters were used, compression/artifact selection or errors were overlooked.
Review mongodump summary, BSON files and metadata manifest.
ResolutionTreat it as failed, correct scope/roles and compare collection counts before accepting.
mongorestore --oplogReplay rejects namespace options.
Likely causeOplog replay requires the complete dump and forbids db/collection/include/exclude/from/to filters.
mongorestore --helpInspect dump root for oplog.bson
ResolutionRestore the full dump into isolation, or omit oplog replay and explicitly accept different consistency semantics.
mongorestore reports incompatible server version.
Likely causeDestination major version or FCV differs from source.
db.version()db.adminCommand({getParameter:1,featureCompatibilityVersion:1})mongorestore --version
ResolutionProvision a compatible same-major/FCV restore target and follow supported upgrade after validation.
Restore collection counts match but indexes/validators differ.
Likely causeMetadata files were omitted, restore errors ignored or unsupported feature/version altered metadata.
getIndexes()listCollections with optionsmongorestore logs
ResolutionRepeat complete metadata restore on compatible version and fail application acceptance until indexes/validators match.
Restore with --drop would remove unexpected data.
Likely causeDestination is not empty/quarantined or namespace scope is misunderstood.
List destination databases/collections and deployment identity.
ResolutionStop immediately and provision a clean isolated target; never use --drop on an unverified production URI.
Reference
Frequently asked questions
Why does this guide use three data-bearing members instead of an arbiter?
Three data-bearing members keep an odd voting majority while retaining three copies of the dataset. An arbiter participates in elections but stores no data, so it does not improve read capacity, backup coverage, or recovery from the loss of a data-bearing member. Use an arbiter only after reviewing MongoDB's topology guidance and accepting that trade-off explicitly.
Does majority write concern mean that a separate MongoDB backup is unnecessary?
No. Majority acknowledgement reduces the chance that an accepted write is rolled back during a replica-set election, but deletion, corruption, faulty application writes, and compromised credentials can affect every replica. A backup must live in an independent failure domain and prove its value through an isolated restore test.
Can I enable authentication on an existing unauthenticated production deployment in one step?
Treat that as a staged migration, not a configuration toggle. Inventory every client, create and test identities through MongoDB's documented transition procedure, distribute secrets securely, and prove that monitoring and backup jobs authenticate before enforcement. Keep recovery access and a reviewed rollback plan; never expose an unauthenticated listener while preparing the migration.
Are the certificates used by replica-set members the same as application user credentials?
Not in this design. Member certificates establish internal X.509 identity and encrypted transport between mongod processes. Applications use narrowly scoped SCRAM users over validated TLS unless a separately reviewed X.509 client-authentication design is chosen. Keep the member PKI lifecycle and database-user lifecycle independently auditable.
Is mongodump --oplog a point-in-time backup for every MongoDB deployment?
No. It captures a full replica-set logical dump plus operations that occur during that dump, allowing oplog replay for that complete dump. It is not the generic procedure for a sharded cluster, cannot be combined with namespace filters for oplog replay, does not support every encrypted-data feature, and may be too disruptive for large datasets. Choose snapshots or a supported continuous-backup product when those constraints do not fit.
Can I restore a dump directly into a different MongoDB major version?
Do not assume cross-major compatibility. Provision a destination supported by the Database Tools documentation, normally matching the source major version and Feature Compatibility Version, complete the isolated restore and semantic checks, and only then perform a separately documented MongoDB upgrade. Record the server, FCV, and Database Tools versions with every backup artifact.
Should mongorestore also replace users and roles in the recovery environment?
That is an explicit recovery-policy decision. Restoring authentication metadata can recreate obsolete or overly broad access, while omitting it requires identities to be recreated from reviewed configuration. Test both the data restore and the chosen identity-recovery path, then run positive and negative authorization checks before any application reconnects.
How do I know that a successful mongodump is actually recoverable?
A zero exit code is only the first signal. Record the dump summary and versions, checksum the completed artifact, encrypt and retain it independently, restore it into an empty isolated compatible replica set, replay the oplog when applicable, and verify counts, representative documents, indexes, validators, identity policy, and application invariants inside the required RPO and RTO.
Recovery
Rollback
Do not disable authorization/TLS or delete replica metadata as rollback. Remove application traffic, preserve logs/config/data, restore the last reviewed configuration one member at a time or build an isolated replacement from a verified backup. Rotate exposed credentials and certificates.
- Stop new writes through the application layer when split topology, authorization exposure, corruption or restore mismatch is suspected.
- Preserve rs.status/config, optimes, FCV/version, logs, package state, TLS metadata, users/roles metadata and storage evidence from all members.
- For config/certificate regression, validate the prior reviewed files on an isolated member and roll one secondary at a time, preserving majority.
- For credential exposure, create replacement user/certificate, update clients, verify new access, revoke old material and audit prior use.
- Never use force reconfig while a majority is available; follow MongoDB's documented disaster procedure only for genuine majority loss.
- For logical corruption or deletion, restore a known-good artifact in quarantine, replay only validated application events and compare semantics.
- Return traffic only after TLS/auth negative tests, one-primary/two-secondary health, majority writes, lag/oplog, monitoring and backup restore pass.
Evidence