Mongodb 简明教程

MongoDB - Create Backup

在本章中,我们将了解如何在 MongoDB 中创建备份。

In this chapter, we will see how to create a backup in MongoDB.

Dump MongoDB Data

若要创建 MongoDB 中数据库的备份,你应使用 mongodump 命令。此命令将把你的服务器的全部数据转储到转储目录。可以使用许多选项来限制数据量或创建远程服务器的备份。

To create backup of database in MongoDB, you should use mongodump command. This command will dump the entire data of your server into the dump directory. There are many options available by which you can limit the amount of data or create backup of your remote server.

Syntax

mongodump 命令的基本语法如下:

The basic syntax of mongodump command is as follows −

>mongodump

Example

启动你的 mongod 服务器。假设你的 mongod 服务器在 localhost 和端口 27017 上运行,则请打开命令提示符并转到 mongodb 实例的 bin 目录,然后键入命令 mongodump

Start your mongod server. Assuming that your mongod server is running on the localhost and port 27017, open a command prompt and go to the bin directory of your mongodb instance and type the command mongodump

考虑 mycol 集合具有以下数据。

Consider the mycol collection has the following data.

>mongodump

此命令将连接到在 127.0.0.1 和端口 27017 上运行的服务器,并将服务器的所有数据备份到目录 /bin/dump/ 。以下是该命令的输出:

The command will connect to the server running at 127.0.0.1 and port 27017 and back all data of the server to directory /bin/dump/. Following is the output of the command −

mongodump

以下是可与 mongodump 命令一起使用的可用选项列表。

Following is a list of available options that can be used with the mongodump command.

Syntax

Description

Example

mongodump --host HOST_NAME --port PORT_NUMBER

This commmand will backup all databases of specified mongod instance.

mongodump --host tutorialspoint.com --port 27017

mongodump --dbpath DB_PATH --out BACKUP_DIRECTORY

This command will backup only specified database at specified path.

mongodump --dbpath /data/db/ --out /data/backup/

mongodump --collection COLLECTION --db DB_NAME

This command will backup only specified collection of specified database.

mongodump --collection mycol --db test

Restore data

要还原备份数据,请使用 MongoDB 的 mongorestore 指令。此指令将从备份目录还原所有数据。

To restore backup data MongoDB’s mongorestore command is used. This command restores all of the data from the backup directory.

Syntax

mongorestore 指令的基本语法为:

The basic syntax of mongorestore command is −

>mongorestore

以下为指令输出:

Following is the output of the command −

mongorestore