How to Use mongorestore to Restore MongoDB Data
Use
mongorestore to restore MongoDB data from a backup directory or BSON files by running mongorestore [options] <backup_directory>. It connects to your MongoDB server and imports the saved data into the specified database.Syntax
The basic syntax of mongorestore is:
mongorestore [options] <backup_directory>- restores data from the specified backup folder.--db <database_name>- specifies the target database to restore into.--drop- drops each collection before restoring it.--host <hostname>- specifies the MongoDB server address.--port <port_number>- specifies the port number of the MongoDB server.
bash
mongorestore [options] <backup_directory> mongorestore --db mydb --drop /path/to/backup
Example
This example restores a backup from the folder dump/mydb into the database mydb on the local MongoDB server. It drops existing collections before restoring to avoid duplicates.
bash
mongorestore --db mydb --drop dump/mydb
Output
2024-06-01T12:00:00.000+0000 connected to: mongodb://localhost:27017/
2024-06-01T12:00:00.100+0000 dropping: mydb.collection1
2024-06-01T12:00:00.200+0000 restoring mydb.collection1 from dump/mydb/collection1.bson
2024-06-01T12:00:00.300+0000 restored mydb.collection1 (100 documents)
2024-06-01T12:00:00.400+0000 finished restoring mydb
Common Pitfalls
Common mistakes when using mongorestore include:
- Not using
--dropwhen you want to replace existing data, causing duplicate documents. - Restoring to the wrong database if
--dbis omitted. - Incorrect backup path leading to errors like "no files to restore".
- Not matching MongoDB server version compatibility with the backup.
Always verify the backup path and use --drop if you want a clean restore.
bash
mongorestore dump/mydb # Might append data causing duplicates mongorestore --db mydb --drop dump/mydb # Correct way to replace data
Quick Reference
| Option | Description |
|---|---|
| --db | Restore data into the specified database |
| --drop | Drop collections before restoring them |
| --host | Specify MongoDB server host (default: localhost) |
| --port | Specify MongoDB server port (default: 27017) |
| Path to the backup folder containing BSON files |
Key Takeaways
Use
mongorestore with the backup folder path to restore MongoDB data.Add
--drop to remove existing data before restoring to avoid duplicates.Specify the target database with
--db to control where data is restored.Ensure the backup path is correct and accessible to avoid errors.
Check MongoDB server compatibility with your backup files before restoring.