How to Backup MongoDB Database: Simple Steps and Examples
To backup a MongoDB database, use the
mongodump command-line tool which creates a binary export of your data. Run mongodump --db yourDatabaseName --out /path/to/backup to save the backup files to a folder.Syntax
The mongodump command exports the contents of a MongoDB database into BSON files. Key parts include:
--db: specifies the database name to backup.--out: specifies the directory where backup files will be saved.--host: optional, specifies the MongoDB server address.--port: optional, specifies the server port.
bash
mongodump --db <database_name> --out <backup_directory>
Example
This example backs up the database named mydb to a folder called backup in the current directory.
bash
mongodump --db mydb --out ./backup
Output
2024-06-01T12:00:00.000+0000 writing mydb.collection1 to ./backup/mydb/collection1.bson
2024-06-01T12:00:00.100+0000 writing mydb.collection2 to ./backup/mydb/collection2.bson
Dump completed successfully.
Common Pitfalls
Common mistakes when backing up MongoDB include:
- Not specifying the
--dboption, which causesmongodumpto backup all databases, possibly creating large files. - Backing up while the database is heavily written to, which can cause inconsistent backups.
- Not having write permissions to the backup directory.
Always ensure you have enough disk space and consider stopping writes or using a replica set for consistent backups.
bash
mongodump --out ./backup
# This backs up all databases, which might be unintended.
mongodump --db mydb --out ./backup
# Correct: backs up only the 'mydb' database.Quick Reference
| Option | Description | Example |
|---|---|---|
| --db | Specify database name to backup | --db mydb |
| --out | Directory to save backup files | --out ./backup |
| --host | MongoDB server address | --host localhost |
| --port | MongoDB server port | --port 27017 |
| --gzip | Compress backup files | --gzip |
Key Takeaways
Use mongodump with --db and --out options to backup a specific MongoDB database.
Ensure you have write permissions and enough disk space for the backup folder.
Avoid backing up during heavy write operations to prevent inconsistent backups.
Use --gzip to compress backups and save storage space.
Backing up all databases without --db can create large files unintentionally.