mongorestore 是一个工具,可读取 mongodump 二进制导出并将数据恢复到 MongoDB 部署。使用 mongorestore 从 mongodump 备份恢复分片集群。
开始之前
确保您的源集群已经有 mongodump 备份。要创建一个,请参阅 使用数据库转储备份自管理分片集群。如果您有文件系统快照,请参阅 从快照恢复自管理分片集群。
步骤
1
停止负载均衡器。
为防止数据块迁移干扰恢复,请连接到 mongos 并停止负载均衡器:
sh.stopBalancer()
要验证您已停止了负载均衡器,请运行:
use config while( sh.isBalancerRunning().mode != "off" ) { print( "Waiting for Balancer to stop..." ); sleep( 1000 ); }
2
在目标集群上对集合进行分片前处理。
对于源集群中的每个分片集合,请在恢复数据之前,在目标集群上创建集合并使用相同的分片键对其进行分片。
要查找每个集合的分片键,请查询活的源集群:
use config db.collections.find()
或者,您可以使用 bsondump 检查转储目录中的 config/collections.bson 文件:
bsondump /path/to/dump/config/collections.bson
{ "_id": "<database>.<collection>", ... "key": { "<shardKeyField>": "<key>" }, ... }
注意
有效的分片键值为 1 或 "hashed"。
对于每个分片集合,使用相同的分片键在目标集群上对集合进行分片:
sh.shardCollection( "<database-name>.<collection-name>", { <shardKeyField>: <key> } )
3
恢复集群。
使用 mongorestore 连接到 mongos 并恢复集群。排除 config 数据库以保留目标集群的现有配置:
mongorestore \ --host <host> \ --port 27017 \ --username <username> \ --password "<password>" \ --authenticationDatabase admin \ --nsExclude='config.*' \ /path/to/backup
重要
--drop 选项在恢复之前删除集合。如果在预分片集合后使用 --drop,mongorestore 将删除分片配置。
5
验证集群可访问性。
连接到 mongos 并运行 sh.status() 以检查整个集群状态:
sh.status()
要确认所有分片均可访问和通信,请将测试文档插入临时集合中:
db.testRestore.insertOne({ test: 1 })
然后连接到每个分片主节点 (primary node in the replica set)并运行 db.collection.find() 以确认文档存在:
db.testRestore.find()