MongoDB provides backup and restore facilities to protect database data from accidental deletion, hardware failure, corruption, or other problems.
1. Backup in MongoDB
Backup means creating a copy of the MongoDB database so that it can be restored later if the original data is lost or damaged.
MongoDB mainly provides the following backup methods:
A. mongodump
mongodump is a command-line utility used to create a binary backup of MongoDB databases.
Syntax:
mongodump --db database_name --out backup_folder
Example:
mongodump --db college --out C:\backup
This creates a backup of the college database inside the C:\backup folder.
To back up all databases:
mongodump --out C:\backup
B. Backup of a Specific Collection
mongodump --db college --collection students --out C:\backup
This backs up only the students collection from the college database.
2. Restore in MongoDB
Restore means recovering the database from a previously created backup.
MongoDB provides the mongorestore utility for restoring backups created using mongodump.
Syntax
mongorestore --db database_name backup_folder
Example
Suppose the backup is stored in:
C:\backup\college
Restore it using:
mongorestore --db college C:\backup\college
3. Backup and Restore Example
Suppose we have a database:
college
with a collection:
students
Step 1: Create Backup
mongodump --db college --out C:\MongoBackup
Step 2: Delete or Lose the Database
For example:
use college
db.dropDatabase()
Now the college database is deleted.
Step 3: Restore the Database
mongorestore --db college C:\MongoBackup\college
The database and its collections are restored from the backup.
4. Important MongoDB Backup Commands
| Command | Purpose |
|---|---|
mongodump | Creates a binary backup |
mongorestore | Restores a mongodump backup |
mongoexport | Exports collection data in JSON/CSV format |
mongoimport | Imports JSON/CSV data into MongoDB |
mongoexport Example
mongoexport --db geet --collection emp --out c:\backup\emp.json
mongoimport Example
mongoimport --db geet --collection emp --file c:\backup\emp.json
5. Difference Between mongodump and mongoexport
mongodump | mongoexport |
|---|---|
| Creates MongoDB binary backup | Exports data to JSON/CSV |
| Mainly used for backup and recovery | Mainly used for data exchange |
| Preserves MongoDB data types better | May not preserve all MongoDB-specific types |
Restored using mongorestore | Imported using mongoimport |
In simple words:
Backup:
MongoDB Database → mongodump → Backup
Restore:
Backup → mongorestore → MongoDB Database
Exam definition:
MongoDB Backup and Restore Facility is a mechanism used to create copies of MongoDB data and recover that data when the original database is lost, damaged, or accidentally deleted. The
mongodumputility is used for backup, whilemongorestoreis used for restoration.