mongorestore is a tool that reads mongodump binary exports and restores the data to a MongoDB deployment. Use mongorestore to restore a sharded cluster from a mongodump backup.
开始之前
Ensure you have a mongodump backup of your source cluster. To create one, see Back Up a Self-Managed Sharded Cluster with a Database Dump. If you have file system snapshots, see Restore a Self-Managed Sharded Cluster from Snapshots.
步骤
停止负载均衡器。
为防止数据块迁移干扰恢复,请连接到 mongos 并停止负载均衡器:
sh.stopBalancer()
要验证您已停止了负载均衡器,请运行:
use config while( sh.isBalancerRunning().mode != "off" ) { print( "Waiting for Balancer to stop..." ); sleep( 1000 ); }
在目标集群上对集合进行分片前处理。
对于源集群中的每个分片集合,请在恢复数据之前,在目标集群上创建集合并使用相同的分片键对其进行分片。
要查找每个集合的分片键,请查询活的源集群:
use config db.collections.find()
Alternatively, you can use bsondump to inspect the config/collections.bson file from your dump directory:
bsondump /path/to/dump/config/collections.bson
{ "_id": "<database>.<collection>", ... "key": { "<shardKeyField>": "<key>" }, ... }
注意
有效的分片键值为 1 或 "hashed"。
对于每个分片集合,使用相同的分片键在目标集群上对集合进行分片:
sh.shardCollection( "<database-name>.<collection-name>", { <shardKeyField>: <key> } )
恢复集群。
Use mongorestore to connect to mongos and restore the cluster. Exclude the config database to preserve the destination cluster's existing configuration:
mongorestore \ --host <host> \ --port 27017 \ --username <username> \ --password "<password>" \ --authenticationDatabase admin \ --nsExclude='config.*' \ /path/to/backup
重要
The --drop option drops the collection before restoring. If you use --drop after pre-sharding collections, mongorestore removes the sharding configuration.
验证集群可访问性。
连接到 mongos 并运行 sh.status() 以检查整个集群状态:
sh.status()
要确认所有分片均可访问和通信,请将测试文档插入临时集合中:
db.testRestore.insertOne({ test: 1 })
然后连接到每个分片主节点 (primary node in the replica set)并运行 db.collection.find() 以确认文档存在:
db.testRestore.find()