1 简述
MongoDB 的安装目录下提供了一系列数据库的操作与检测工具,备份与恢复程序也在其中。MongoDB 提供的备份与恢复程序是一种静态备份与恢复工具,可用于数据迁移。
2 MongoDB 备份
(1)备份全库
备份命令:
mongodump --database <database name>
--user <database username>
--password <database password>
[--gzip]
[--archive=<directory/filename.suffixName>]
参数
--database
或者-d
指定需要备份的数据库名--user
或者-u
指定数据库授权用户(若数据库不要求授权用户,缺省该选项)--password
或者-p
密码 (若数据库不要求授权用户,缺省该选项)--gzip
指定备份文件压缩格式为 gzip--archive
归档,将所有的表备份到一个文档中
例子
mongodump --database testDB
--user testUser
--password testPassword
--gzip
--archive=/usr/local/backup/backupfile.subffix # 若路径或文件名中包含空格,一定要加双引号
# 或者
mongodump -d mtp -u mtpuser -p Passw0rd
--gzip --archive=/var/opt/backup/backupfile.subffix
(2)备份部分数据库表,排除不需要的数据表
mongodump --db testDB --excludeCollection=tab1 --excludeCollection=tab2
参数
--
excludeCollection 指定需要排除的表- ... 其它命令上同
3 MongoDB 恢复
(1)恢复全库
恢复命令
mongostore --authenticationDatabase <database-name>
--user <database username>
--password <database password>
[--gzip]
[--archive=<directory/filename.suffixName>]
[--drop]
参数
-
--authenticationDatabase 指定恢复时需要授权的数据库
-
--drop
指定备份数据表之前删除原有的数据表,相当于覆盖恢复。从备份文件中恢复数据表之前,删掉目标数据库中原来的表数据,--drop 只会删除需要恢复的表的数据,不会删除不需要恢复的数据表的数据。 -
... 其它参数同备份的参数一样
例子
mongorestore --authenticationDatabase testDB
-u testUser
-p testPassword
--archive=/var/opt/backup/backupfile.subffix
--gzip # 与备份时命令对应
--drop # 覆盖恢复
(2)恢复部分表,排除不需要的表
mongorestore --authenticationDatabase testDB
-u testUser
-p testPassword
--archive=/var/opt/backup/backupfile.subffix
--gzip
--drop
--nsExclude testDB.tab1
--nsExclude testDB.tab2
(3)恢复指定表
mongorestore --authenticationDatabase testDB
-u testUser
-p testPassword
--archive=/var/opt/backup/backupfile.subffix
--gzip
--drop
--nsInclude testDB.tab1
参数
-
--nsExclude 指定不需要恢复的表
-
--nsInclude 指定需要恢复的表
-
... 其它参数上同
4 总结
上面描述的功能只是备份与恢复的少部分功能,参考更多详情见Mongo manual, backup and restore。