How to Restore MongoDB Database Quickly and Easily
To restore a MongoDB database, use the
mongorestore command with the path to your backup directory or BSON files. This command reloads the data into your MongoDB server from the backup.Syntax
The basic syntax of the mongorestore command is:
mongorestore [options] <backup_directory>
Here:
backup_directoryis the folder containing the backup files.--db <database_name>specifies the target database to restore.--dropoption drops the existing database before restoring.
bash
mongorestore --db <database_name> --drop <backup_directory>
Example
This example restores a database named mydb from a backup folder dump/mydb. It drops the existing mydb database before restoring to avoid conflicts.
bash
mongorestore --db mydb --drop dump/mydb
Output
2024-06-01T12:00:00.000+0000 connected to: mongodb://localhost:27017/
2024-06-01T12:00:01.000+0000 dropping: mydb.collection
2024-06-01T12:00:02.000+0000 restoring mydb.collection from dump/mydb/collection.bson
2024-06-01T12:00:03.000+0000 finished restoring mydb
Common Pitfalls
- Not using
--dropcan cause duplicate data if the database already exists. - Restoring to the wrong database name if
--dbis omitted. - Backup directory path must be correct and accessible.
- MongoDB server must be running before restoring.
bash
mongorestore dump/mydb # Might restore to original database but can cause duplicates mongorestore --db mydb dump/mydb # Correct target database mongorestore --db mydb --drop dump/mydb # Safest to avoid duplicates
Quick Reference
| Option | Description |
|---|---|
| --db | Specify the database to restore to |
| --drop | Drop the database before restoring |
| Path to the backup files | |
| --host | MongoDB server address (default localhost) |
| --port | MongoDB server port (default 27017) |
Key Takeaways
Use
mongorestore with the backup folder path to restore MongoDB data.Include
--drop to remove existing data before restoring to avoid duplicates.Specify the target database with
--db to control where data is restored.Ensure MongoDB server is running and backup path is correct before restoring.
Check for common mistakes like wrong paths or missing options to prevent errors.