mongodump 的参数与 mongoexport(数据导出)的参数基本一致:
备份工具同导入导出工具类似,都是在命令行进行操作,无需进入客户端。
编程测试代码:
mkdir /opt/mongodb
mkdir /opt/mongodb_1
mkdir /opt/mongodb_2
mkdir /opt/collection_1
mkdir /opt/collection_2
mongoimport -d test2 -c student -file /home/example/student.csv --type csv
mongoimport -d test1 -c person --type json --file /home/example/person.json
(如果数据库未设置用户和密码,可以省略 -uroot -proot 参数)
将所有数据库备份到 /opt/mongodb 目录下
mongodump -h 127.0.0.1:27017 --authenticationDatabase admin -o /opt/mongodb
将 test1 数据库备份到 /opt/mongodb_1 目录下
mongodump -h 127.0.0.1:27017 --authenticationDatabase admin -d test1 -o /opt/mongodb_1
将 person 集合备份到 /opt/collection_1 目录下
mongodump -h 127.0.0.1:27017 --authenticationDatabase admin -d test1 -c person -o /opt/collection_1
将 student 集合压缩备份到 /opt/collection_2 目录下
mongodump -h 127.0.0.1:27017 --authenticationDatabase admin -d test2 -c student -o /opt/collection_2 --gzip
将 test2 数据库压缩备份到 /opt/mongodb_2 目录下
mongodump -h 127.0.0.1:27017 --authenticationDatabase admin -d test2 -o /opt/mongodb_2 --gzip
将 /opt/mongodb 目录下的数据恢复到 MongoDB 中;
mongorestore -h 127.0.0.1:27017 --authenticationDatabase admin --drop /opt/mongodb
将 /opt/mongodb_1 目录下的数据恢复到 mytest1 数据库中
mongorestore -h 127.0.0.1:27017 --authenticationDatabase admin -d mytest1 /opt/mongodb_1/test1
将 /opt/collection_1 目录下的数据恢复到 mytest2 数据库的 person 集合中
mongorestore -h 127.0.0.1:27017 --authenticationDatabase admin -d mytest2 -c person /opt/collection_1/test1/person.bson
将 /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
将/opt/mongodb_2目录下的数据恢复到mytest4 的数据库中,并删除之前的备份的数据库
mongorestore -h 127.0.0.1:27017 --authenticationDatabase admin -d mytest4 --gzip --drop /opt/mongodb_2/test2/student.bson.gz