Easy Tutorial
❮ Mongodb Intro Mongodb Tutorial ❯

MongoDB Backup (mongodump) and Restore (mongorestore)


MongoDB Data Backup

In MongoDB, we use the mongodump command to back up MongoDB data. This command exports all data to a specified directory.

The mongodump command can specify the amount of data to export and the server to dump.

Syntax

The mongodump command script syntax is as follows:

>mongodump -h dbhost -d dbname -o dbdirectory

--h:

MongoDB server address, for example: 127.0.0.1, or specify a port number: 127.0.0.1:27017

--d:

Database instance to be backed up, for example: test

--o:

Location to store the backup data, for example: c:\data\dump. The directory needs to be created in advance. After the backup is complete, the system automatically creates a directory named after the database instance within the dump directory, which contains the backup data.

Example

Start your mongod service locally using port 27017. Open the command prompt window, navigate to the MongoDB installation directory's bin directory, and enter the command mongodump:

>mongodump

After executing the command, the client connects to the MongoDB service at 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 mongodump command optional parameter list is shown below:

Syntax Description Example
mongodump --host HOST_NAME --port PORT_NUMBER This command backs up all MongoDB data mongodump --host tutorialpro.org --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 specified database collection. mongodump --collection mycol --db test

MongoDB Data Restore

MongoDB uses the mongorestore command to restore backed-up data.

Syntax

The mongorestore command script syntax is as follows:

>mongorestore -h <hostname><:port> -d dbname <path>

---host

MongoDB server address, default: localhost:27017

---db

Database instance to be restored, for example: test, although this name can be different from the backup name, such as test2

---drop:

When restoring, delete the current data first, then restore the backed-up data. This means that data added or modified after the backup will be deleted. Use with caution!

-<path>:

The last parameter of mongorestore, sets the location of the backup data, for example: c:\data\dump\test.

You cannot specify both <path> and --dir options, --dir can also set the backup directory.

---dir:

Specifies the backup directory

You cannot specify both <path> and --dir options.

Next, we execute the following command:

>mongorestore

The output result of executing the above command is as follows:

❮ Mongodb Intro Mongodb Tutorial ❯