1. Introduction š±
Even the most well-optimized MongoDB deployment is only as safe as its backup and recovery strategy. Data loss, corruption, and accidental deletions happen ā what determines the outcome is whether you can restore quickly and reliably.
This tutorial covers backup fundamentals, the mongodump/mongorestore toolchain, Atlas-managed backups, data migration strategies, and disaster recovery planning for MongoDB deployments used with Node.js applications.
Important
2. Backup Fundamentals š§±
MongoDB backups generally fall into two categories, each suited to different recovery needs.
| Factor | Logical | Physical |
|---|---|---|
| Speed (large datasets) | Slower | Faster |
| Portability | High | Lower (engine-dependent) |
| Granularity | Database/collection level | Whole data directory |
3. Backup Strategies š
- Full backupsā complete copy of all data at a point in time.
- Incremental backupsā capture only changes since the last backup (used by Atlas continuous backups).
- Point-in-time recoveryā restore to any specific moment using the oplog.
Best Practice
4. Logical Backups š
Logical backups export data as BSON documents, independent of the underlying storage engine, making them highly portable across MongoDB versions.
terminal
mongodump --uri="mongodb://localhost:27017" --db=shopDB --out=./backupTip
5. Physical Backups š½
Physical backups copy the raw data files directly from disk (or via filesystem/volume snapshots), making them much faster for very large datasets.
- LVM or cloud-provider volume snapshots (e.g., EBS snapshots).
- db.fsyncLock() / db.fsyncUnlock() to safely flush and lock writes before a filesystem snapshot.
fsync-lock.js
await db.admin().command({ fsync: 1, lock: true });
// ... take filesystem snapshot here ...
await db.admin().command({ fsyncUnlock: 1 });Warning
6. mongodump š¤
terminal
# Back up an entire deployment
mongodump --uri="mongodb://localhost:27017" --out=./backup
# Back up a specific collection
mongodump --uri="mongodb://localhost:27017" --db=shopDB --collection=orders --out=./backup
# Back up with a query filter
mongodump --db=shopDB --collection=orders --query='{"status":"completed"}' --out=./backupNote
7. mongorestore š„
terminal
# Restore an entire dump directory
mongorestore --uri="mongodb://localhost:27017" ./backup
# Restore into a different database name
mongorestore --uri="mongodb://localhost:27017" --nsFrom="shopDB.*" --nsTo="shopDB_staging.*" ./backup
# Drop existing collections before restoring
mongorestore --drop ./backupCaution
8. mongoexport š
mongoexport exports collections to JSON or CSV, useful for interoperability with non-MongoDB tools, unlike the binary BSON format used by mongodump.
terminal
mongoexport --uri="mongodb://localhost:27017" --db=shopDB --collection=users --out=users.jsonWarning
9. mongoimport šØ
terminal
mongoimport --uri="mongodb://localhost:27017" --db=shopDB --collection=users --file=users.json
# Import with upsert on a unique field
mongoimport --db=shopDB --collection=users --file=users.json --mode=upsert --upsertFields=emailTip
10. BSON Export šļø
BSON is MongoDB's native binary format and preserves all data types exactly, making it the preferred format for true backups.
terminal
mongodump --db=shopDB --collection=orders --out=./bson-backup
# Produces: bson-backup/shopDB/orders.bson + orders.metadata.jsonReference
11. JSON Export š
terminal
mongoexport --db=shopDB --collection=products --out=products.json --jsonArray --pretty- Useful for sharing data with external systems or non-technical stakeholders.
- Use --jsonArray to produce a single valid JSON array instead of newline-delimited JSON.
12. CSV Import & Export š
terminal
# Export to CSV with specific fields
mongoexport --db=shopDB --collection=users --type=csv --fields=name,email,age --out=users.csv
# Import from CSV
mongoimport --db=shopDB --collection=users --type=csv --headerline --file=users.csvTip
13. Atlas Backups āļø
MongoDB Atlas provides fully managed, continuous cloud backups with configurable retention policies, eliminating the need to manage mongodump cron jobs manually.
- Continuous backupsā capture changes continuously for fine-grained point-in-time recovery.
- Scheduled snapshotsā periodic full snapshots retained per policy (e.g., daily, weekly, monthly).
- Cross-region backup copiesā for disaster recovery against regional outages.
Best Practice
14. Point-in-Time Recovery ā±ļø
PIT recovery uses the oplogto restore a database to an exact moment, down to the second ā critical for recovering from accidental deletions or bad deploys.
pit-restore-concept.txt
1. Restore the most recent full snapshot before the target time
2. Replay oplog entries up to the exact target timestamp
3. Verify data consistency post-restoreImportant
15. Snapshot Backups šø
terminal
# Example: AWS EBS snapshot after fsyncLock
aws ec2 create-snapshot --volume-id vol-0123456789abcdef0 --description "MongoDB backup $(date +%F)"- Lock writes with fsyncLock() (for standalone/non-journaled setups) or use a replica set secondary to avoid impacting primary traffic.
- Trigger the volume snapshot at the storage layer.
- Unlock writes with fsyncUnlock() once the snapshot completes.
Tip
16. Restore Strategies š
terminal
# Restore to a staging environment first for validation
mongorestore --uri="mongodb://staging-host:27017" ./backup
# Restore a single collection from a full dump
mongorestore --nsInclude="shopDB.orders" ./backup- Always restore to a staging/test environment first before restoring to production.
- Use --nsInclude/--nsExclude for selective, targeted restores.
- Document and rehearse restore steps as part of a disaster recovery runbook.
17. Data Validation ā
After any backup or restore, validate data integrity before considering the operation complete.
validation.js
// Compare document counts between source and restored target
const sourceCount = await sourceDb.collection('orders').countDocuments();
const restoredCount = await targetDb.collection('orders').countDocuments();
if (sourceCount !== restoredCount) {
console.error('ā ļø Document count mismatch after restore!');
}
// MongoDB's built-in validation command
const result = await db.collection('orders').validate({ full: true });Warning
18. Database Migration š
Migrationcovers moving data between environments ā on-premise to Atlas, between cloud regions, or between MongoDB versions.
Tip
19. Schema Migration šļø
Since MongoDB is schema-flexible, migrations often involve transforming existing documents to a new shape rather than altering rigid table definitions.
schema-migration.js
// Add a new field with a default value to all existing documents
await db.collection('users').updateMany(
{ role: { $exists: false } },
{ $set: { role: 'customer' } }
);
// Rename a field across the collection
await db.collection('users').updateMany(
{},
{ $rename: { 'fullname': 'name' } }
);Best Practice
20. Version Upgrades ā¬ļø
- Read the release notes for breaking changes between your current and target versions.
- Upgrade one major version at a timeā skipping versions is unsupported.
- Update the featureCompatibilityVersion only after confirming stability on the new version.
- Upgrade replica set members in a rolling fashion, starting with secondaries.
fcv-check.js
const fcv = await db.admin().command({ getParameter: 1, featureCompatibilityVersion: 1 });
console.log(fcv.featureCompatibilityVersion);Danger
21. Cross-Cluster Migration š
terminal
# Dump from source cluster
mongodump --uri="mongodb+srv://user:pass@source-cluster.mongodb.net" --out=./migration
# Restore to target cluster
mongorestore --uri="mongodb+srv://user:pass@target-cluster.mongodb.net" ./migrationTip
22. Zero-Downtime Migration š
Achieving zero-downtime migration typically combines an initial bulk copy with real-time change replication via change streams.
zero-downtime-migration.js
// 1. Initial bulk copy (source ā target)
const docs = await sourceDb.collection('orders').find({}).toArray();
await targetDb.collection('orders').insertMany(docs);
// 2. Stream ongoing changes during the cutover window
const changeStream = sourceDb.collection('orders').watch();
changeStream.on('change', async (change) => {
if (change.operationType === 'insert') {
await targetDb.collection('orders').insertOne(change.fullDocument);
}
// handle update/delete operationTypes similarly
});- Perform an initial bulk sync of existing data.
- Use change streams to replicate ongoing writes during the migration window.
- Cut over application traffic once the target is fully caught up.
23. Disaster Recovery š
A disaster recovery (DR)plan defines how quickly and completely you can recover from catastrophic failure ā region outage, ransomware, or catastrophic human error.
- RPOā maximum acceptable data loss, measured in time.
- RTOā maximum acceptable time to restore service.
- Cross-region replica set members or cross-region Atlas backup copies for regional failover.
Important
24. Best Practices ā
- Automate backups ā never rely on manual, ad-hoc mongodump runs for production.
- Test restores regularly in a staging environment, not just when disaster strikes.
- Encrypt backup files both in transit and at rest.
- Store backups in a geographically separate location from the primary deployment.
- Maintain a documented, rehearsed disaster recovery runbook.
25. Common Mistakes š«
| Mistake | Consequence |
|---|---|
| Never testing restore procedures | Backups may be corrupt or incomplete when actually needed |
| Using mongoexport as a primary backup | Loss of BSON type fidelity (dates, ObjectIds) |
| Skipping major versions during upgrades | Unsupported upgrade path, potential data corruption |
| Storing backups on the same infrastructure as production | Single point of failure during regional outages |
| No documented RPO/RTO targets | Unclear expectations during an actual incident |
Caution
26. Frequently Asked Questions ā
Question
Answer
Question
Answer
Question
Answer
27. Summary š
Summary
- Official Docs: mongodump Documentation
- Atlas Backups: Atlas Backup & Restore