mongodb server version: 7.0.12 社區版
mongo shell version: 2.2.10
平臺:win10 64位
控制臺:Git Bash
分片相關節點結構示意圖
大概步驟
1. 配置 配置服務器 副本集 (最少3個節點)
-- 創建數據目錄
mkdir -p ~/dbs/config1 ~/dbs/config2 ~/dbs/config3
-- 啟動配置服務器
./mongod.exe --dbpath ~/dbs/config1 --port 20001 --replSet cfgrs1/localhost:20002 --configsvr
./mongod.exe --dbpath ~/dbs/config2 --port 20002 --replSet cfgrs1/localhost:20001 --configsvr
./mongod.exe --dbpath ~/dbs/config3 --port 20003 --replSet cfgrs1/localhost:20001 --configsvr
./mongosh.exe localhost:20001/local
-- 初始化副本集
rs.initiate({_id: "cfgrs1",version: 1,members: [{ _id: 0, host : "localhost:20001" },{ _id: 1, host : "localhost:20002" },{ _id: 2, host : "localhost:20003" }]}
)
-- 查看副本集
db.system.replset.find()
2. 配置 分片服務器 副本集 (最少3個節點)
-- 創建數據目錄
mkdir -p ~/dbs/shard1 ~/dbs/shard2 ~/dbs/shard3
-- 啟動分片服務器
./mongod.exe --dbpath ~/dbs/shard1 --port 10001 --replSet shardrs1/localhost:10002 --shardsvr
./mongod.exe --dbpath ~/dbs/shard2 --port 10002 --replSet shardrs1/localhost:10001 --shardsvr
./mongod.exe --dbpath ~/dbs/shard3 --port 10003 --replSet shardrs1/localhost:10001 --shardsvr
./mongosh.exe localhost:10001/local
-- 初始化副本集
rs.initiate({_id: "shardrs1",version: 1,members: [{ _id: 0, host : "localhost:10001" },{ _id: 1, host : "localhost:10002" },{ _id: 2, host : "localhost:10003" }]}
)
-- 查看副本集
db.system.replset.find()
-- 查看是否位主節點
rs.isMaster()
3. 啟動mongs
./mongos.exe --configdb cfgrs1/localhost:20001,localhost:20002,localhost:20003 --port 30000
4. 啟動mongo shell,連接mongos服務器,切換到admin數據庫,配置分片
-- 連接mongos
./mongosh.exe localhost:30000/admin-- 添加分片
db.runCommand({addShard:"shardrs1/localhost:10001,localhost:10002,localhost:10003",allowLocal:true})-- 開啟數據庫級別支持分片
db.runCommand({"enableSharding":"foo"})-- 開啟集合級別支持分片
db.runCommand({"shardCollection":"foo.bar","key":{"_id":1}})-- 切換到 config 數據庫
use config-- 查看分片db.shards.find()-- 查看數據塊
db.chunks.find()-- 測試插入數據
use foo
db.bar.insertOne({"name":"Tom","age":9})
db.bar.find()