MongoDB Backup (mongodump) and Restore (mongorestore)
MongoDB data backup
In MongoDB we use the mongodump command to back up MongoDB data. This command can export all data to a specified directory.
The mongodump command can specify the level of data to export and the server to dump to through parameters.
Syntax
The mongodump command script syntax is as follows:
>mongodump -h dbhost -d dbname -o dbdirectory
- ** -h:**
The address of the server where MongoDB is located, for example: 127.0.0.1; of course you can also specify a port number: 127.0.0.1:27017
- ** -d:**
The database instance to back up, for example: test
- ** -o:**
The location where the backup data is stored, for example: c:\data\dump. Of course, this directory needs to be created in advance. After the backup is complete, the system automatically creates a test directory under the dump directory, which stores the backup data of the database instance.
Example
Start your mongod service locally using 27017. Open a command prompt window, enter the bin directory of the MongoDB installation directory, and type the command mongodump:
>mongodump
After running the above command, the client connects to the MongoDB service with IP 127.0.0.1 and port 27017, and backs up all data to the bin/dump/ directory. The command output is as follows:

The list of optional parameters for the mongodump command is as follows:
| Syntax | Description | Example |
|---|---|---|
| mongodump --host HOST_NAME --port PORT_NUMBER | This command backs up all MongoDB data | mongodump --host runoob.com --port 27017 |
| mongodump --dbpath DB_PATH --out BACKUP_DIRECTORY | mongodump --dbpath /data/db/ --out /data/backup/ | |
| mongodump --collection COLLECTION --db DB_NAME | This command backs up the collections of the specified database. | mongodump --collection mycol --db test |
MongoDB data restoration
MongoDB uses the mongorestore command to restore backed-up data.
Syntax
The mongorestore command script syntax is as follows:
>mongorestore -h <:port> -d dbname
- ** --host
<:port>, -h **<:port>: The address of the server where MongoDB is located, default: localhost:27017
- ** --db
, -d **: The database instance to restore, for example: test. Of course, this name can also be different from the one used during backup, such as test2
- ** --drop:**
When restoring, the current data is deleted first, and then the backed-up data is restored. That is to say, after restoration, any data added or modified after the backup will be deleted; use with caution!
- **
:** The last parameter of mongorestore sets the location of the backup data, for example: c:\data\dump\test.
You cannot specify both
and the --dir option at the same time; --dir can also set the backup directory. - ** --dir:**
Specify the backup directory
You cannot specify both
and --dir option.
Next, we execute the following command:
>mongorestore
The output of the above command is as follows:
