5-1MongoDB 实验——数据备份和恢复

第1关:数据备份

mongodump 备份工具

mongodump 的参数与 mongoexport(数据导出)的参数基本一致:

参数参数说明
-h指明数据库宿主机的IP
-u指明数据库的用户名
-p指明数据库的密码
-d指明数据库的名字
-c指明collection的名字
-o指明到要导出的文件名
-q指明导出数据的过滤条件
--authenticationDatabase验证数据的名称
--gzip备份时压缩
--oploguse 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;

image-20211023210601174

将所有数据库备份到 /opt/mongodb 目录下

mkdir -p /opt/mongodb
mongodump -h localhost:27017 --authenticationDatabase admin  -o  /opt/mongodb 

image-20211023212209527

将 test1 数据库备份到 /opt/mongodb_1 目录下

mkdir -p /opt/mongodb_1
mongodump -h localhost:27017 --authenticationDatabase admin  -d test1 -o /opt/mongodb_1

image-20211023212342811

将 person 集合备份到 /opt/collection_1 目录下

mkdir -p /opt/collection_1
mongodump -h localhost:27017 --authenticationDatabase admin  -d test1 -c person -o /opt/collection_1

image-20211023212509568

将 student 集合压缩备份到 /opt/collection_2 目录下

mkdir -p /opt/collection_2
mongodump -h localhost:27017 --authenticationDatabase admin  -d test2 -c student -o /opt/collection_2

image-20211023212941151

将 test2 数据库压缩备份到 /opt/mongodb_2 目录下

mkdir -p /opt/mongodb_2
mongodump -h localhost:27017 --authenticationDatabase admin  -d test2 -o /opt/mongodb_2 --gzip

image-20211023213114952

第2关:数据恢复

mongorestore 恢复工具

参数参数说明
-h指明数据库宿主机的IP
-u指明数据库的用户名
-p指明数据库的密码
-d指明数据库的名字
-c指明collection的名字
-o指明到要导出的文件名
-q指明导出数据的过滤条件
--authenticationDatabase验证数据的名称
--gzip备份时压缩
--oploguse oplog for taking a point-in-time snapshot
--drop恢复的时候把之前的集合drop掉

将 /opt/mongodb 目录下的数据恢复到 MongoDB 中;

mongorestore -h localhost:27017 --authenticationDatabase admin --drop /opt/mongodb

image-20211023213641736

将 /opt/mongodb_1 目录下的数据恢复到 mytest1 数据库中

mongorestore -h localhost:27017 --authenticationDatabase admin -d mytest1 /opt/mongodb_1/test1

image-20211023213748840

将 /opt/collection_1 目录下的数据恢复到 mytest2 数据库的 person 集合中

mongorestore -h localhost:27017 --authenticationDatabase admin -d mytest2 -c person /opt/collection_1/test1/person.bson

image-20211023213827733

将 /opt/collection_2 目录下的数据恢复到 mytest3 数据库的 student 集合中,并删除之前备份的表

mongorestore -h localhost:27017 --authenticationDatabase admin -d mytest3 -c student --drop /opt/collection_2/test2/student.bson 

image-20211023213927250

将 /opt/mongodb_2 目录下的数据恢复到 mytest4 的数据库中,并删除之前的备份的数据库

mongorestore -h localhost:27017 --authenticationDatabase admin -d mytest4 --gzip --drop /opt/mongodb_2/test2

image-20211023214013519

最后修改:2021 年 10 月 23 日 09 : 41 PM