5-1MongoDB 实验——数据备份和恢复
第1关:数据备份
mongodump 备份工具
mongodump 的参数与 mongoexport(数据导出)的参数基本一致:
参数 | 参数说明 |
---|---|
-h | 指明数据库宿主机的IP |
-u | 指明数据库的用户名 |
-p | 指明数据库的密码 |
-d | 指明数据库的名字 |
-c | 指明collection的名字 |
-o | 指明到要导出的文件名 |
-q | 指明导出数据的过滤条件 |
--authenticationDatabase | 验证数据的名称 |
--gzip | 备份时压缩 |
--oplog | use oplog for taking a point-in-time snapshot |
分别将 /home/example 目录下的 person.json 和 student.csv 导入到 MongoDB 的 test1 数据库的 person 集合、test2 数据库的 student 集合
mongoimport -d test1 -c person --type json --file /home/example/person.json;
mongoimport -d test2 -c student --type csv --headerline --file /home/example/student.csv;
将所有数据库备份到 /opt/mongodb 目录下
mkdir -p /opt/mongodb
mongodump -h localhost:27017 --authenticationDatabase admin -o /opt/mongodb
将 test1 数据库备份到 /opt/mongodb_1 目录下
mkdir -p /opt/mongodb_1
mongodump -h localhost:27017 --authenticationDatabase admin -d test1 -o /opt/mongodb_1
将 person 集合备份到 /opt/collection_1 目录下
mkdir -p /opt/collection_1
mongodump -h localhost:27017 --authenticationDatabase admin -d test1 -c person -o /opt/collection_1
将 student 集合压缩备份到 /opt/collection_2 目录下
mkdir -p /opt/collection_2
mongodump -h localhost:27017 --authenticationDatabase admin -d test2 -c student -o /opt/collection_2
将 test2 数据库压缩备份到 /opt/mongodb_2 目录下
mkdir -p /opt/mongodb_2
mongodump -h localhost:27017 --authenticationDatabase admin -d test2 -o /opt/mongodb_2 --gzip
第2关:数据恢复
mongorestore 恢复工具
参数 | 参数说明 |
---|---|
-h | 指明数据库宿主机的IP |
-u | 指明数据库的用户名 |
-p | 指明数据库的密码 |
-d | 指明数据库的名字 |
-c | 指明collection的名字 |
-o | 指明到要导出的文件名 |
-q | 指明导出数据的过滤条件 |
--authenticationDatabase | 验证数据的名称 |
--gzip | 备份时压缩 |
--oplog | use oplog for taking a point-in-time snapshot |
--drop | 恢复的时候把之前的集合drop掉 |
将 /opt/mongodb 目录下的数据恢复到 MongoDB 中;
mongorestore -h localhost:27017 --authenticationDatabase admin --drop /opt/mongodb
将 /opt/mongodb_1 目录下的数据恢复到 mytest1 数据库中
mongorestore -h localhost:27017 --authenticationDatabase admin -d mytest1 /opt/mongodb_1/test1
将 /opt/collection_1 目录下的数据恢复到 mytest2 数据库的 person 集合中
mongorestore -h localhost:27017 --authenticationDatabase admin -d mytest2 -c person /opt/collection_1/test1/person.bson
将 /opt/collection_2 目录下的数据恢复到 mytest3 数据库的 student 集合中,并删除之前备份的表
mongorestore -h localhost:27017 --authenticationDatabase admin -d mytest3 -c student --drop /opt/collection_2/test2/student.bson
将 /opt/mongodb_2 目录下的数据恢复到 mytest4 的数据库中,并删除之前的备份的数据库
mongorestore -h localhost:27017 --authenticationDatabase admin -d mytest4 --gzip --drop /opt/mongodb_2/test2