3.25. MongoDB backup (mongodump) and recovery (mongorestore)

发布时间 : 2025-10-25 13:34:21 UTC      

Page Views: 9 views

3.25.1. MongoDB data backup

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

The mongodump command can specify the server for rollover of the exported data magnitude through parameters.

Grammar

The mongodump command script syntax is as follows:

>mongodump -h dbhost -d dbname -o dbdirectory 
  • -h: The address of the server where MongoDB resides, for example: 127.0.0.1. Of course, you can also specify the port number: 127.0.0.1 27017.

  • -d: Database instance that needs to be backed up, for example: test

  • -o: The location of the backup data, for example: C:datadump. Of course, this directory needs to be established in advance. After the backup is completed, the system automatically creates a test directory under the dump directory, in which the backup data of the database instance is stored.

Example

Start your mongod service locally with 27017. Open a command prompt window and enter the command mongodump in the bin directory of the MongoDB installation directory:

>mongodump 

After executing the above command, the client connects to the MongoDB service with ip 127.0.0.1 port number 27017 and backs up all data to the bin/dump/ directory. The output of the command is as follows:

MongoDB data backup

The list of optional parameters for the mongodump command is as follows:

Grammar

Description

Example

Mongodump-host HOST_NAME-port PORT_NUMBER

This command will back 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 collection of the specified database.

Mongodump-collection mycol-db test

3.25.2. MongoDB data recovery

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

Grammar

The mongorestore command script syntax is as follows:

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