MongoDB Backup: Complete Guide to Backing Up and Restoring Your Database in 2026
Losing a MongoDB database without a backup is one of the most painful experiences any developer or system administrator can face. Whether it is an accidental db.dropCollection(), a ransomware attack, a failed migration, or a corrupted storage volume β without a solid backup strategy in place, the data is simply gone.
This guide covers everything you need to know about MongoDB backup β from the built-in tools that ship with MongoDB itself, to Docker-based backup workflows, automated scheduling, and a tested restore process you can rely on when things go wrong.
Why MongoDB Backup Strategy Matters
MongoDB stores data differently from relational databases. Its document-based, schema-flexible nature means that a single collection can hold millions of documents with varying structures β and a single misconfigured update or delete operation can wipe out data across the entire collection in milliseconds.
Common scenarios where a MongoDB backup saves you:
- Accidental data deletion β
db.collection.drop()ordeleteMany({})with a wrong filter - Ransomware and security breaches β attackers encrypting or wiping MongoDB instances (extremely common on exposed port 27017)
- Failed application deployments β a bad migration script corrupts production data
- Hardware or cloud storage failure β disk corruption or VM snapshot failures
- Compliance requirements β GDPR, HIPAA, and SOC2 all require data backup and recovery documentation
A good MongoDB backup strategy follows the 3-2-1 rule:
- 3 copies of the data
- 2 different storage media
- 1 copy stored offsite (cloud or remote server)
MongoDB Backup Methods Overview
MongoDB provides several backup approaches, each suited for different use cases:
| Method | Tool | Best For | Downtime Required |
|---|---|---|---|
| Logical Backup | mongodump | Small to medium databases | No |
| Logical Restore | mongorestore | Restoring from mongodump backups | Brief |
| File System Snapshot | LVM / Cloud Snapshots | Large databases | No |
| MongoDB Atlas Backup | Atlas UI | Cloud-hosted MongoDB deployments | No |
| Ops Manager / Cloud Manager | Enterprise tool | Large enterprise deployments | No |
mongoexport | Built-in CLI | Single collection export to JSON or CSV | No |
This guide focuses on mongodump and mongorestore β the most widely used tools available in all MongoDB editions, including Community Edition.
1. Understanding mongodump β The Primary Backup Tool
mongodump is a utility that creates a binary export of the contents of a MongoDB instance. It connects to a running MongoDB instance and outputs BSON files that can later be restored with mongorestore.
Basic mongodump Syntax
# Backup the entire MongoDB instance
mongodump --out /backup/mongodb/
# Backup a specific database
mongodump --db myapp_production --out /backup/mongodb/
# Backup a specific collection
mongodump --db myapp_production --collection users --out /backup/mongodb/
# Backup with authentication
mongodump \
--host localhost \
--port 27017 \
--username admin \
--password "YourPassword123" \
--authenticationDatabase admin \
--db myapp_production \
--out /backup/mongodb/
Output Structure
/backup/mongodb/
βββ myapp_production/
βββ users.bson # Collection data in binary format
βββ users.metadata.json # Collection metadata (indexes, options)
βββ orders.bson
βββ orders.metadata.json
βββ products.bson
Compressed Backup (Recommended)
Always compress backups to save disk space β MongoDB BSON files compress extremely well:
# Create compressed backup archive
mongodump \
--db myapp_production \
--archive=/backup/mongodb/myapp_$(date +%Y%m%d_%H%M%S).gz \
--gzip
# Verify the backup file
ls -lh /backup/mongodb/
# Output: myapp_20260615_143022.gz (much smaller than uncompressed)
2. Restoring with mongorestore
mongorestore reads the BSON files created by mongodump and inserts the data back into a MongoDB instance.
Basic Restore Syntax
# Restore entire backup to the same instance
mongorestore /backup/mongodb/
# Restore a specific database
mongorestore --db myapp_production /backup/mongodb/myapp_production/
# Restore with drop (replaces existing data β use with caution)
mongorestore --drop --db myapp_production /backup/mongodb/myapp_production/
# Restore from compressed archive
mongorestore \
--archive=/backup/mongodb/myapp_20260615_143022.gz \
--gzip
# Restore with authentication
mongorestore \
--host localhost \
--port 27017 \
--username admin \
--password "YourPassword123" \
--authenticationDatabase admin \
--db myapp_production \
--drop \
/backup/mongodb/myapp_production/
Important: The
--dropflag drops the existing collection before restoring. Without it,mongorestorewill insert documents alongside existing ones β which may cause duplicate key errors if unique indexes exist.
Restore a Specific Collection Only
# Restore only the users collection from a full backup
mongorestore \
--db myapp_production \
--collection users \
/backup/mongodb/myapp_production/users.bson
3. Backup MongoDB Running in Docker
If your MongoDB instance runs in a Docker container, the backup workflow is slightly different β you run mongodump inside the container using docker exec.
One-line Docker Backup Command
# Backup MongoDB running in Docker container
docker exec mongodb-container mongodump \
--username admin \
--password "YourPassword123" \
--authenticationDatabase admin \
--archive \
--gzip > /backup/mongodb/myapp_$(date +%Y%m%d_%H%M%S).gz
Docker Compose MongoDB Backup
If you are running MongoDB with Docker Compose:
# docker-compose.yml
version: "3.9"
services:
mongodb:
image: mongo:7.0
container_name: mongodb
environment:
MONGO_INITDB_ROOT_USERNAME: admin
MONGO_INITDB_ROOT_PASSWORD: YourPassword123
volumes:
- mongodb-data:/data/db
- ./backup:/backup
ports:
- "127.0.0.1:27017:27017" # Only accessible locally β never expose to internet
networks:
- app-network
networks:
app-network:
driver: bridge
volumes:
mongodb-data:
# Backup using docker compose exec
docker compose exec mongodb mongodump \
--username admin \
--password "YourPassword123" \
--authenticationDatabase admin \
--archive \
--gzip > /backup/mongodb/myapp_$(date +%Y%m%d_%H%M%S).gz
# Verify backup file is not empty
ls -lh /backup/mongodb/*.gz
Restore to Docker MongoDB
# Restore from a compressed backup into Docker MongoDB
docker exec -i mongodb-container mongorestore \
--username admin \
--password "YourPassword123" \
--authenticationDatabase admin \
--archive \
--gzip \
--drop < /backup/mongodb/myapp_20260615_143022.gz
4. Automate MongoDB Backups with Cron
Manual backups are not a backup strategy β they are a wish. Automate with a cron job and a backup script.
Create a Backup Script
sudo nano /usr/local/bin/mongodb-backup.sh
#!/bin/bash
# MongoDB Automated Backup Script
# bckinfo.com | 2026
# Configuration
MONGO_HOST="localhost"
MONGO_PORT="27017"
MONGO_USER="admin"
MONGO_PASSWORD="YourPassword123"
MONGO_AUTH_DB="admin"
BACKUP_DIR="/backup/mongodb"
RETENTION_DAYS=7
DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="$BACKUP_DIR/mongodb_backup_$DATE.gz"
LOG_FILE="/var/log/mongodb-backup.log"
# Create backup directory if it doesn't exist
mkdir -p "$BACKUP_DIR"
echo "[$DATE] Starting MongoDB backup..." >> "$LOG_FILE"
# Run mongodump
mongodump \
--host "$MONGO_HOST" \
--port "$MONGO_PORT" \
--username "$MONGO_USER" \
--password "$MONGO_PASSWORD" \
--authenticationDatabase "$MONGO_AUTH_DB" \
--archive="$BACKUP_FILE" \
--gzip
# Check if backup was successful
if [ $? -eq 0 ]; then
echo "[$DATE] Backup successful: $BACKUP_FILE ($(du -sh $BACKUP_FILE | cut -f1))" >> "$LOG_FILE"
else
echo "[$DATE] ERROR: Backup failed!" >> "$LOG_FILE"
exit 1
fi
# Delete backups older than RETENTION_DAYS
find "$BACKUP_DIR" -name "mongodb_backup_*.gz" -mtime +$RETENTION_DAYS -delete
echo "[$DATE] Cleaned up backups older than $RETENTION_DAYS days" >> "$LOG_FILE"
echo "[$DATE] Backup process completed." >> "$LOG_FILE"
# Make the script executable
sudo chmod +x /usr/local/bin/mongodb-backup.sh
# Test the script manually first
sudo /usr/local/bin/mongodb-backup.sh
# Verify output
cat /var/log/mongodb-backup.log
ls -lh /backup/mongodb/
Schedule with Cron
# Open crontab editor
sudo crontab -e
# Add these lines:
# Daily backup at 2:00 AM
0 2 * * * /usr/local/bin/mongodb-backup.sh
# Weekly full backup every Sunday at 1:00 AM (optional)
0 1 * * 0 /usr/local/bin/mongodb-backup.sh
5. Export and Import Single Collections with mongoexport
For simpler use cases β exporting data for analysis, migrating a single collection, or sharing data with a team β mongoexport is more practical than mongodump.
# Export a collection to JSON
mongoexport \
--db myapp_production \
--collection users \
--out /backup/users_export.json \
--username admin \
--password "YourPassword123" \
--authenticationDatabase admin
# Export to CSV (specify fields explicitly)
mongoexport \
--db myapp_production \
--collection users \
--type csv \
--fields name,email,createdAt \
--out /backup/users_export.csv
# Export with a query filter
mongoexport \
--db myapp_production \
--collection orders \
--query '{"status": "completed", "createdAt": {"$gte": {"$date": "2026-01-01T00:00:00Z"}}}' \
--out /backup/completed_orders_2026.json
Import back with mongoimport:
# Import JSON back into MongoDB
mongoimport \
--db myapp_production \
--collection users \
--file /backup/users_export.json \
--username admin \
--password "YourPassword123" \
--authenticationDatabase admin
# Import with upsert (update if exists, insert if not)
mongoimport \
--db myapp_production \
--collection users \
--file /backup/users_export.json \
--mode upsert \
--upsertFields email
6. Verify Your Backups β Never Assume They Work
A backup you have never tested is not a backup β it is a hypothesis. Regularly verify that your backups can actually be restored.
# Create a test restore script
#!/bin/bash
BACKUP_FILE="/backup/mongodb/mongodb_backup_latest.gz"
TEST_DB="restore_test_$(date +%Y%m%d)"
echo "Testing restore of $BACKUP_FILE into database $TEST_DB..."
mongorestore \
--username admin \
--password "YourPassword123" \
--authenticationDatabase admin \
--nsFrom "myapp_production.*" \
--nsTo "$TEST_DB.*" \
--archive="$BACKUP_FILE" \
--gzip
if [ $? -eq 0 ]; then
echo "Restore test PASSED."
# Count documents in restored database to verify
mongo --username admin --password "YourPassword123" \
--authenticationDatabase admin \
--eval "db.getSiblingDB('$TEST_DB').getCollectionNames().forEach(function(c) { print(c + ': ' + db.getSiblingDB('$TEST_DB').getCollection(c).countDocuments() + ' documents') })"
# Drop the test database after verification
mongo --username admin --password "YourPassword123" \
--authenticationDatabase admin \
--eval "db.getSiblingDB('$TEST_DB').dropDatabase()"
echo "Test database $TEST_DB dropped after verification."
else
echo "Restore test FAILED. Investigate immediately."
exit 1
fi
Schedule this test restore script to run weekly β ideally on a separate test server or environment.
7. Security Best Practices for MongoDB Backups
MongoDB backups often contain sensitive data. Treat them with the same security rigor as production databases.
# Encrypt backup files with GPG
gpg --symmetric --cipher-algo AES256 /backup/mongodb/myapp_20260615.gz
# Enter and confirm a passphrase
# Output: myapp_20260615.gz.gpg
# Decrypt when needed
gpg --decrypt /backup/mongodb/myapp_20260615.gz.gpg > /backup/mongodb/myapp_20260615.gz
Additional backup security measures:
# Restrict backup directory permissions β only root can access
sudo chown root:root /backup/mongodb
sudo chmod 700 /backup/mongodb
# Verify permissions
ls -la /backup/
# Expected: drwx 2 root root ... mongodb
# Never expose MongoDB port 27017 to the internet
# Always bind to localhost or a private network
# In /etc/mongod.conf:
net:
port: 27017
bindIp: 127.0.0.1 # localhost only
MongoDB Backup Checklist
[ ] mongodump runs successfully with --gzip compression
[ ] Backup files stored outside the MongoDB data directory
[ ] Automated cron job configured (daily minimum)
[ ] Retention policy set (delete backups older than 7β30 days)
[ ] Backup script writes to a log file
[ ] Test restore performed successfully at least once
[ ] Weekly restore verification scheduled
[ ] Backup files encrypted (GPG or equivalent)
[ ] Backup directory permissions restricted (chmod 700)
[ ] MongoDB port 27017 NOT exposed to the internet
[ ] At least one offsite backup copy (cloud storage, remote server)
[ ] Backup size and log monitored for anomalies
Conclusion
MongoDB backups are not complicated β but they require deliberate setup and regular testing. The most common mistake is assuming that a backup exists without ever verifying it can actually be restored.
Start with a mongodump cron job running nightly, compressed with --gzip, and stored in a directory outside the MongoDB data path. From there, add encryption, offsite copies, and a weekly restore test to build a backup strategy you can genuinely rely on.
A backup you have never restored is not a backup. Test it before you need it.
Have a specific MongoDB setup or backup scenario you want to discuss? Leave a comment below.



