MongoDB 实验——数据备份和恢复
第1关:数据备份
mongodump 备份工具
mongodump 的参数与 mongoexport(数据导出)的参数基本一致:

使用 mongodump 备份数据
备份工具同导入导出工具类似,都是在命令行进行操作,无需进入客户端。
编程测试代码:
mkdir /opt/mongodb
mkdir /opt/mongodb_1
mkdir /opt/mongodb_2
mkdir /opt/collection_1
mkdir /opt/collection_2
1、导入集合
mongoimport -d test2 -c student -file /home/example/student.csv --type csv
mongoimport -d test1 -c person --type json --file /home/example/person.json
2、全库备份
(如果数据库未设置用户和密码,可以省略 -uroot -proot 参数)
将所有数据库备份到 /opt/mongodb 目录下
mongodump -h 127.0.0.1:27017 --authenticationDatabase admin -o /opt/mongodb

3、单个数据库备份:
将 test1 数据库备份到 /opt/mongodb_1 目录下
mongodump -h 127.0.0.1:27017 --authenticationDatabase admin -d test1 -o /opt/mongodb_1

4、集合备份:
将 person 集合备份到 /opt/collection_1 目录下
mongodump -h 127.0.0.1:27017 --authenticationDatabase admin -d test1 -c person -o /opt/collection_1

5、压缩备份集合:
将 student 集合压缩备份到 /opt/collection_2 目录下
mongodump -h 127.0.0.1:27017 --authenticationDatabase admin -d test2 -c student -o /opt/collection_2 --gzip

6、压缩备份库:
将 test2 数据库压缩备份到 /opt/mongodb_2 目录下
mongodump -h 127.0.0.1:27017 --authenticationDatabase admin -d test2 -o /opt/mongodb_2 --gzip

第2关:数据恢复

1、全库备份中恢复单库
将 /opt/mongodb 目录下的数据恢复到 MongoDB 中;
mongorestore -h 127.0.0.1:27017 --authenticationDatabase admin --drop /opt/mongodb

2、恢复到数据库下
将 /opt/mongodb_1 目录下的数据恢复到 mytest1 数据库中
mongorestore -h 127.0.0.1:27017 --authenticationDatabase admin -d mytest1 /opt/mongodb_1/test1

3、恢复到数据库的集合下
将 /opt/collection_1 目录下的数据恢复到 mytest2 数据库的 person 集合中
mongorestore -h 127.0.0.1:27017 --authenticationDatabase admin -d mytest2 -c person /opt/collection_1/test1/person.bson

4、--gzip 、--drop 参数实践恢复
将 /opt/collection_2 目录下的数据恢复到 mytest3 数据库的 student 集合中,并删除之前备份的表;
mongorestore -h 127.0.0.1:27017 --authenticationDatabase admin -d mytest3 -c student --gzip --drop /opt/collection_2/test2/student.bson.gz

5、--gzip 、--drop 参数实践恢复
将/opt/mongodb_2目录下的数据恢复到mytest4 的数据库中,并删除之前的备份的数据库
mongorestore -h 127.0.0.1:27017 --authenticationDatabase admin -d mytest4 --gzip --drop /opt/mongodb_2/test2/student.bson.gz




