这是一个涉及数据库运维的操作,需要谨慎处理。
MongoDB 集群配置删除与重新绑定
1. 理解 MongoDB 集群配置存储位置
MongoDB 集群配置主要存储在 Config Servers 中:
- Config Database (plain复制
config): 包含分片集群的元数据
- Local Database: 每个节点存储的副本集配置
2. 删除集群配置的方法
场景 A: 完全重置分片集群
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| killall mongos
killall mongod
killall mongod
rm -rf /data/configdb/*
mongod --configsvr --replSet configRS --dbpath /data/configdb --port 27019
rs.initiate({ _id: "configRS", configsvr: true, members: [ { _id: 0, host: "cfg1.example.com:27019" }, { _id: 1, host: "cfg2.example.com:27019" }, { _id: 2, host: "cfg3.example.com:27019" } ] })
|
场景 B: 仅移除分片(保留集群框架)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| mongo-- host mongos.example.com-- port 27017
sh.status()
use admin db.runCommand({removeShard: "shard0000"})
db.runCommand({removeShard: "shard0000"})
db.runCommand({removeShard: "shard0000", drop: true})
|
场景 C: 重置副本集配置(非分片集群)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| mongo-- host mongod.example.com-- port 27017
rs.conf()
rs.reconfig({ _id: "myReplicaSet", members: [ {_id: 0, host: "newhost1:27017"}, {_id: 1, host: "newhost2:27017"}, {_id: 2, host: "newhost3:27017"} ] }, {force: true})
use local db.system.replset.remove({})
|
3. 重新绑定新配置
步骤 1: 重新配置 Config Server
1 2 3 4 5 6 7 8 9 10
| rs.initiate({ _id: "configRS", configsvr: true, members: [ {_id: 0, host: "new-cfg1:27019", priority: 2}, {_id: 1, host: "new-cfg2:27019"}, {_id: 2, host: "new-cfg3:27019", arbiterOnly: true} ] })
|
步骤 2: 启动 mongos 并配置分片
1 2
| mongos --configdb configRS/new-cfg1:27019,new-cfg2:27019,new-cfg3:27019 --port 27017
|
1 2 3 4 5 6 7 8 9
| sh.addShard("shardRS1/shard1-node1:27018,shard1-node2:27018") sh.addShard("shardRS2/shard2-node1:27018,shard2-node2:27018")
sh.enableSharding("myDatabase")
sh.shardCollection("myDatabase.myCollection", {shardKey: 1})
|
4. 关键注意事项
| 操作 |
风险等级 |
说明 |
| 删除 Config Server 数据 |
🔴 极高 |
会丢失所有分片元数据 |
| 强制 rs.reconfig |
🟡 中等 |
可能导致脑裂 |
| removeShard |
🟢 较低 |
数据会自动迁移 |
| 停止 mongos |
🟢 低 |
仅影响路由,不丢数据 |
5. 安全操作建议
1 2 3 4
| mongodump --host configRS/cfg1:27019 --db config --out /backup/config_$(date +%Y%m%d)
|
6. 常见问题排查
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| use admin db.runCommand({getShardMap: 1})
sh.status()
sh.getBalancerState()
use admin db.adminCommand({flushRouterConfig: 1})
|
⚠️ 重要提醒:
- 在生产环境执行前,务必在测试环境验证
- 确保有完整的数据备份
- 操作期间会有服务中断,选择维护窗口执行
- 如果是云托管 MongoDB (Atlas),请使用提供商的控制台操作,不要手动修改