Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

MongoDB backup and recovery


May 17, 2021 MongoDB


Table of contents


MongoDB Backup (mongodump) and Recovery (mongorerstore)


MongoDB data backup

In Mongodb we use the Mongodump command to back up MongoDB data. The command can export all data to the specified directory.

The mongodump command can specify the server for the transfer of the exported data magnitude by parameters.

Grammar

The mongodump command script syntax is as follows:

>mongodump -h dbhost -d dbname -o dbdirectory
  • -h:

    MongDB's server address, e.g. 127.0.0.1, can also specify port number: 127.0.0.1:27017

  • -d:

    A database instance that needs to be backed up, for example: test

  • -o:

    The location of the backed up data, for example: c:\data\dump, of course, the directory needs to be established in advance, after the backup is complete, the system automatically establishes a test directory in the dump directory, which holds the backup data of the database instance.

Instance

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

>mongodump

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

MongoDB backup and recovery

The list of optional parameters for the mongodump command looks like this:

Grammar Describe Instance
mongodump --host HOST_NAME --port PORT_NUMBER The command backs up all MongoDB data mongodump --host w3cschool.cn --port 27017
mongodump --dbpath DB_PATH --out BACKUP_DIRECTORY mongodump --dbpath /data/db/ --out /data/backup/
mongodump --collection COLLECTION --db DB_NAME The command backs up the collection of the specified database. mongodump --collection mycol --db test

MongoDB data recovery

Mongodb uses the mongorerstore command to recover the backed up data.

Grammar

The mongorestore command script syntax is as follows:

>mongorestore -h dbhost -d dbname --directoryperdb dbdirectory
  • -h:

    The server address where MongoDB is located

  • -d:

    A database instance that needs to be recovered, such as test, which can of course be a different name than it was at the time of the backup, such as test2

  • --directoryperdb:

    Where the backup data is located, e.g.: c:-data-dump-test, why add one more test here instead of the dump at the time of the backup, and the reader will check the tips themselves!

  • --drop:

    When you recover, delete the current data and then restore the backed up data. That is to say, after recovery, after the backup to add modified data will be deleted, use with caution Oh!

Let's then execute the following command:

>mongorestore

The output of the above commands is as follows:

MongoDB backup and recovery