1、mongodb备份命令 1.1、备份之前查看备份实例的相关数据:
1 2 3 4 5 6 7 8 MongoDB Enterprise testrepl:PRIMARY> use admin switched to db admin MongoDB Enterprise testrepl:PRIMARY> db.auth('admin1','admin123'); 1 MongoDB Enterprise testrepl:PRIMARY> use test; switched to db test MongoDB Enterprise testrepl:PRIMARY> db.test_collection.find().count(); 844703
1.2、对于replica set集群模式命令如下:
1 /data/mongodb/bin/mongodump -h "testrepl/127.0.0.1:30000" -u admin1 -p admin123 -d test -o /data/backup/ --authenticationDatabase admin
结果如下:
1 2 2018 -08 -12T03:40:01.489+0000 writing test.test_collection to 2018 -08 -12T03:40:03.823+0000 done dumping test.test_collection (844703 documents)
会在指定的备份目录下,生成备份实例名对应的文件夹,文件夹下有以下文件:
1 test_collection.bson test_collection.metadata.json
命令参数详解:
1 2 3 4 5 6 7 -h:指定当前备份主机ip --port:指定当前mongodb的启动端口 -u:指定验证的用户名 -d:需要备份的数据库实例 -p:指定用户名对应的密码 -o:指定备份的路径 --authenticationDatabase:认证数据库
备份过程没有加上指定认证数据库“–authenticationDatabase admin”,会报一下错误
1 Failed: error connecting to db server: server returned error on SASL authentication step: Authentication failed.
1.3、对于单节点备份命令如下:
1 /data/mongodb/bin/mongodump -h 127.0 .0 .1 --port 30000 -u admin1 -p admin123 -d test -o /data/backup --authenticationDatabase admin
2、拷贝备份出来的文件,新建一台新节点(10.0.7.36)mongodb,并做恢复测试,恢复命令如下(因为测试环境节点有限,该恢复操作是将一个集群模式的备份,恢复到一个单点上的操作): 1 /data/mongodb/bin/mongorestore -h 10.0.7.36 --port 30000 -u admin1 -p admin123 -d test /data/backup/test --authenticationDatabase admin
恢复输出结果如下:
1 2 3 4 5 6 7 8 9 2018 -08 -11T14:19:48.860+0000 the --db and --collection args should only be used when restoring from a BSON file. Other uses are deprecated and will not exist in the future; use --nsInclude instead 2018 -08 -11T14:19:48.860+0000 building a list of collections to restore from /data/backup/test dir 2018 -08 -11T14:19:48.885+0000 reading metadata for test.test_collection from /data/backup/test/test_collection.metadata.json 2018 -08 -11T14:19:48.972+0000 restoring test.test_collection from /data/backup/test/test_collection.bson 2018 -08 -11T14:19:51.781+0000 [###########.............] test.test_collection 28. 4MB/57.1MB (49.8%) 2018 -08 -11T14:19:54.490+0000 [########################] test.test_collection 57. 1MB/57.1MB (100.0%) 2018 -08 -11T14:19:54.490+0000 restoring indexes for collection test.test_collection from metadata 2018 -08 -11T14:19:57.737+0000 finished restoring test.test_collection (844703 documents) 2018 -08 -11T14:19:57.737+0000 done
控制台登录,查看数据是否一致:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 MongoDB Enterprise > use admin switched to db admin MongoDB Enterprise > db.auth('admin1','admin123'); 1 MongoDB Enterprise > show dbs; admin 0.000GB config 0.000GB local 0.000GB test 0.031GB MongoDB Enterprise > use test switched to db test MongoDB Enterprise > show tables; test_collection MongoDB Enterprise > db.test_collection.find().count(); 844703
恢复完成