mongodb Replica Set集群搭建(三节点)
节点IP分配
192.168.56.107
192.168.56.113
192.168.56.114
准备软件包(所有节点)

创建目录 (所有节点)

准备配置文件
说明:允许从节点处理读操作,在从节点增加如下参数
secondaryOk: true
192.168.56.107
storage:
dbPath: "D:\\mongodb-win32-x86_64-windows-7.0.4\\data"
systemLog:
destination: "file"
path: "D:\\mongodb-win32-x86_64-windows-7.0.4\\logs\\mongodb.log"
net:
bindIp: 192.168.56.107
port: 27017
maxIncomingConnections: 10000
replication:
replSetName: rs0
192.168.56.113
storage:
dbPath: "D:\\mongodb-win32-x86_64-windows-7.0.4\\data"
systemLog:
destination: "file"
path: "D:\\mongodb-win32-x86_64-windows-7.0.4\\logs\\mongodb.log"
net:
bindIp: 192.168.56.114
port: 27016
maxIncomingConnections: 10000
replication:
replSetName: rs0
192.168.56.114
storage:
dbPath: "D:\\mongodb-win32-x86_64-windows-7.0.4\\data"
systemLog:
destination: "file"
path: "D:\\mongodb-win32-x86_64-windows-7.0.4\\logs\\mongodb.log"
net:
bindIp: 192.168.56.113
port: 27013
maxIncomingConnections: 10000
replication:
replSetName: rs0
启动三个节点
mongod --config "D:\mongodb-win32-x86_64-windows-7.0.4\conf\mongodb.cfg" --serviceName MongoDB --serviceDisplayName MongoDB --install
net start MongoDB
连接任意一台数据库
D:\mongosh-2.6.0-win32-x64\bin>mongosh "mongodb://192.168.56.107:27017"
Current Mongosh Log ID: 698b3a9a5f20a9775c628c9f
Connecting to: mongodb://192.168.56.107:27017/?directConnection=true&appName=mongosh+2.6.0
Using MongoDB: 7.0.4
Using Mongosh: 2.6.0
For mongosh info see: https://www.mongodb.com/docs/mongodb-shell/
------
The server generated these startup warnings when booting
2026-02-10T16:32:27.150+08:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
------
test>
初始化集群
cfg={_id:"rs0", members: [ {_id:0,host:'192.168.56.107:27017',priority:2} ,{_id:1,host:'192.168.56.113:27013',priority:1} ,{_id:2,host:'192.168.56.114:27016',arbiterOnly:true}]};
rs.initiate(cfg)
rs.status();
说明:
host:指定的是节点的ip地址与端口号
priority:指的是权重,权重最高的是主节点 ,权重大小的判定(数字最大>数字小的>没有写权重属性的)
arbiterOnly:代表是否作为仲裁节点
D
:\mongosh-2.6.0-win32-x64\bin>mongosh "mongodb://192.168.56.107:27017"
Current Mongosh Log ID: 698b3a9a5f20a9775c628c9f
Connecting to: mongodb://192.168.56.107:27017/?directConnection=true&appName=mongosh+2.6.0
Using MongoDB: 7.0.4
Using Mongosh: 2.6.0
For mongosh info see: https://www.mongodb.com/docs/mongodb-shell/
------
The server generated these startup warnings when booting
2026-02-10T16:32:27.150+08:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
------
test> cfg={_id:"rs0", members: [ {_id:0,host:'192.168.56.107:27017',priority:2} ,{_id:1,host:'192.168.56.113:27013',priority:1} ,{_id:2,host:'192.168.56.114:27016',arbiterOnly:true}]};
{
_id: 'rs0',
members: [
{ _id: 0, host: '192.168.56.107:27017', priority: 2 },
{ _id: 1, host: '192.168.56.113:27013', priority: 1 },
{ _id: 2, host: '192.168.56.114:27016', arbiterOnly: true }
]
}
test>
test> rs.initiate(cfg)
{ ok: 1 }
rs0 [direct: secondary] test>
rs0 [direct: secondary] test> rs.status();
{
set: 'rs0',
date: ISODate('2026-02-10T14:04:10.888Z'),
myState: 1,
term: Long('1'),
syncSourceHost: '',
syncSourceId: -1,
heartbeatIntervalMillis: Long('2000'),
majorityVoteCount: 2,
writeMajorityCount: 2,
votingMembersCount: 3,
writableVotingMembersCount: 2,
optimes: {
lastCommittedOpTime: { ts: Timestamp({ t: 1770732243, i: 7 }), t: Long('1') },
lastCommittedWallTime: ISODate('2026-02-10T14:04:03.194Z'),
readConcernMajorityOpTime: { ts: Timestamp({ t: 1770732243, i: 7 }), t: Long('1') },
appliedOpTime: { ts: Timestamp({ t: 1770732243, i: 7 }), t: Long('1') },
durableOpTime: { ts: Timestamp({ t: 1770732243, i: 7 }), t: Long('1') },
lastAppliedWallTime: ISODate('2026-02-10T14:04:03.194Z'),
lastDurableWallTime: ISODate('2026-02-10T14:04:03.194Z')
},
lastStableRecoveryTimestamp: Timestamp({ t: 1770732230, i: 1 }),
electionCandidateMetrics: {
lastElectionReason: 'electionTimeout',
lastElectionDate: ISODate('2026-02-10T14:04:02.338Z'),
electionTerm: Long('1'),
lastCommittedOpTimeAtElection: { ts: Timestamp({ t: 1770732230, i: 1 }), t: Long('-1') },
lastSeenOpTimeAtElection: { ts: Timestamp({ t: 1770732230, i: 1 }), t: Long('-1') },
numVotesNeeded: 2,
priorityAtElection: 2,
electionTimeoutMillis: Long('10000'),
numCatchUpOps: Long('0'),
newTermStartDate: ISODate('2026-02-10T14:04:02.475Z'),
wMajorityWriteAvailabilityDate: ISODate('2026-02-10T14:04:02.988Z')
},
members: [
{
_id: 0,
name: '192.168.56.107:27017',
health: 1,
state: 1,
stateStr: 'PRIMARY',
uptime: 19906,
optime: { ts: Timestamp({ t: 1770732243, i: 7 }), t: Long('1') },
optimeDate: ISODate('2026-02-10T14:04:03.000Z'),
lastAppliedWallTime: ISODate('2026-02-10T14:04:03.194Z'),
lastDurableWallTime: ISODate('2026-02-10T14:04:03.194Z'),
syncSourceHost: '',
syncSourceId: -1,
infoMessage: 'Could not find member to sync from',
electionTime: Timestamp({ t: 1770732242, i: 1 }),
electionDate: ISODate('2026-02-10T14:04:02.000Z'),
configVersion: 1,
configTerm: 1,
self: true,
lastHeartbeatMessage: ''
},
{
_id: 1,
name: '192.168.56.113:27013',
health: 1,
state: 2,
stateStr: 'SECONDARY',
uptime: 20,
optime: { ts: Timestamp({ t: 1770732243, i: 7 }), t: Long('1') },
optimeDurable: { ts: Timestamp({ t: 1770732243, i: 7 }), t: Long('1') },
optimeDate: ISODate('2026-02-10T14:04:03.000Z'),
optimeDurableDate: ISODate('2026-02-10T14:04:03.000Z'),
lastAppliedWallTime: ISODate('2026-02-10T14:04:03.194Z'),
lastDurableWallTime: ISODate('2026-02-10T14:04:03.194Z'),
lastHeartbeat: ISODate('2026-02-10T14:04:10.452Z'),
lastHeartbeatRecv: ISODate('2026-02-10T14:04:09.409Z'),
pingMs: Long('0'),
lastHeartbeatMessage: '',
syncSourceHost: '192.168.56.107:27017',
syncSourceId: 0,
infoMessage: '',
configVersion: 1,
configTerm: 1
},
{
_id: 2,
name: '192.168.56.114:27016',
health: 1,
state: 7,
stateStr: 'ARBITER',
uptime: 20,
lastHeartbeat: ISODate('2026-02-10T14:04:10.452Z'),
lastHeartbeatRecv: ISODate('2026-02-10T14:04:10.417Z'),
pingMs: Long('0'),
lastHeartbeatMessage: '',
syncSourceHost: '',
syncSourceId: -1,
infoMessage: '',
configVersion: 1,
configTerm: 1
}
],
ok: 1,
'$clusterTime': {
clusterTime: Timestamp({ t: 1770732243, i: 7 }),
signature: {
hash: Binary.createFromBase64('AAAAAAAAAAAAAAAAAAAAAAAAAAA=', 0),
keyId: Long('0')
}
},
operationTime: Timestamp({ t: 1770732243, i: 7 })
}
rs0 [direct: primary] test>
测试登录主从
mongosh "mongodb://192.168.56.107:27017"
D:\mongosh-2.6.0-win32-x64\bin>mongosh "mongodb://192.168.56.107:27017"
Current Mongosh Log ID: 698b3d37a4ce9a857e628c9f
Connecting to: mongodb://192.168.56.107:27017/?directConnection=true&appName=mongosh+2.6.0
Using MongoDB: 7.0.4
Using Mongosh: 2.6.0
For mongosh info see: https://www.mongodb.com/docs/mongodb-shell/
------
The server generated these startup warnings when booting
2026-02-10T16:32:27.150+08:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
------
rs0 [direct: primary] test> exit
mongosh "mongodb://192.168.56.113:27013"
D:\mongosh-2.6.0-win32-x64\bin>mongosh "mongodb://192.168.56.113:27013"
Current Mongosh Log ID: 698b49fdf5a5d6f930628c9f
Connecting to: mongodb://192.168.56.113:27013/?directConnection=true&appName=mongosh+2.6.0
Using MongoDB: 7.0.4
Using Mongosh: 2.6.0
For mongosh info see: https://www.mongodb.com/docs/mongodb-shell/
------
The server generated these startup warnings when booting
2026-02-10T16:29:31.285+08:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
------
rs0 [direct: secondary] test> exit
mongosh "mongodb://192.168.56.114:27016"
D:\mongosh-2.6.0-win32-x64\bin>mongosh "mongodb://192.168.56.114:27016"
Current Mongosh Log ID: 698b4a0a3aa7c61154628c9f
Connecting to: mongodb://192.168.56.114:27016/?directConnection=true&appName=mongosh+2.6.0
Using MongoDB: 7.0.4
Using Mongosh: 2.6.0
For mongosh info see: https://www.mongodb.com/docs/mongodb-shell/
------
The server generated these startup warnings when booting
2026-02-10T16:29:26.854+08:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
2026-02-10T22:03:51.238+08:00: ** WARNING: Arbiters are not supported in quarterly binary versions
------
rs0 [direct: arbiter] test>
查看节点配置
rs0 [direct: arbiter] test> rs.conf()
{
_id: 'rs0',
version: 1,
term: 1,
members: [
{
_id: 0,
host: '192.168.56.107:27017',
arbiterOnly: false,
buildIndexes: true,
hidden: false,
priority: 2,
tags: {},
secondaryDelaySecs: Long('0'),
votes: 1
},
{
_id: 1,
host: '192.168.56.113:27013',
arbiterOnly: false,
buildIndexes: true,
hidden: false,
priority: 1,
tags: {},
secondaryDelaySecs: Long('0'),
votes: 1
},
{
_id: 2,
host: '192.168.56.114:27016',
arbiterOnly: true,
buildIndexes: true,
hidden: false,
priority: 0,
tags: {},
secondaryDelaySecs: Long('0'),
votes: 1
}
],
protocolVersion: Long('1'),
writeConcernMajorityJournalDefault: true,
settings: {
chainingAllowed: true,
heartbeatIntervalMillis: 2000,
heartbeatTimeoutSecs: 10,
electionTimeoutMillis: 10000,
catchUpTimeoutMillis: -1,
catchUpTakeoverDelayMillis: 30000,
getLastErrorModes: {},
getLastErrorDefaults: { w: 1, wtimeout: 0 },
replicaSetId: ObjectId('698b3ac636c0e40ea3e5f66c')
}
}
rs0 [direct: arbiter] test>
##查看节点的状态
rs0 [direct: arbiter] test> rs.status()
{
set: 'rs0',
date: ISODate('2026-02-10T15:14:28.395Z'),
myState: 7,
term: Long('1'),
syncSourceHost: '',
syncSourceId: -1,
heartbeatIntervalMillis: Long('2000'),
majorityVoteCount: 2,
writeMajorityCount: 2,
votingMembersCount: 3,
writableVotingMembersCount: 2,
optimes: {
lastCommittedOpTime: { ts: Timestamp({ t: 1770736464, i: 1 }), t: Long('1') },
lastCommittedWallTime: ISODate('2026-02-10T15:14:24.033Z'),
readConcernMajorityOpTime: { ts: Timestamp({ t: 1770736464, i: 1 }), t: Long('1') },
appliedOpTime: { ts: Timestamp({ t: 1770736464, i: 1 }), t: Long('1') },
durableOpTime: { ts: Timestamp({ t: 0, i: 0 }), t: Long('-1') },
lastAppliedWallTime: ISODate('2026-02-10T15:14:24.033Z'),
lastDurableWallTime: ISODate('1970-01-01T00:00:00.000Z')
},
lastStableRecoveryTimestamp: Timestamp({ t: 0, i: 0 }),
electionParticipantMetrics: {
votedForCandidate: true,
electionTerm: Long('1'),
lastVoteDate: ISODate('2026-02-10T14:04:02.340Z'),
electionCandidateMemberId: 0,
voteReason: '',
lastAppliedOpTimeAtElection: { ts: Timestamp({ t: 1770732230, i: 1 }), t: Long('-1') },
maxAppliedOpTimeInSet: { ts: Timestamp({ t: 1770732230, i: 1 }), t: Long('-1') },
priorityAtElection: 0
},
members: [
{
_id: 0,
name: '192.168.56.107:27017',
health: 1,
state: 1,
stateStr: 'PRIMARY',
uptime: 4237,
optime: { ts: Timestamp({ t: 1770736464, i: 1 }), t: Long('1') },
optimeDurable: { ts: Timestamp({ t: 1770736464, i: 1 }), t: Long('1') },
optimeDate: ISODate('2026-02-10T15:14:24.000Z'),
optimeDurableDate: ISODate('2026-02-10T15:14:24.000Z'),
lastAppliedWallTime: ISODate('2026-02-10T15:14:24.033Z'),
lastDurableWallTime: ISODate('2026-02-10T15:14:24.033Z'),
lastHeartbeat: ISODate('2026-02-10T15:14:27.304Z'),
lastHeartbeatRecv: ISODate('2026-02-10T15:14:27.940Z'),
pingMs: Long('0'),
lastHeartbeatMessage: '',
syncSourceHost: '',
syncSourceId: -1,
infoMessage: '',
electionTime: Timestamp({ t: 1770732242, i: 1 }),
electionDate: ISODate('2026-02-10T14:04:02.000Z'),
configVersion: 1,
configTerm: 1
},
{
_id: 1,
name: '192.168.56.113:27013',
health: 1,
state: 2,
stateStr: 'SECONDARY',
uptime: 4237,
optime: { ts: Timestamp({ t: 1770736464, i: 1 }), t: Long('1') },
optimeDurable: { ts: Timestamp({ t: 1770736464, i: 1 }), t: Long('1') },
optimeDate: ISODate('2026-02-10T15:14:24.000Z'),
optimeDurableDate: ISODate('2026-02-10T15:14:24.000Z'),
lastAppliedWallTime: ISODate('2026-02-10T15:14:24.033Z'),
lastDurableWallTime: ISODate('2026-02-10T15:14:24.033Z'),
lastHeartbeat: ISODate('2026-02-10T15:14:26.690Z'),
lastHeartbeatRecv: ISODate('2026-02-10T15:14:27.624Z'),
pingMs: Long('0'),
lastHeartbeatMessage: '',
syncSourceHost: '192.168.56.107:27017',
syncSourceId: 0,
infoMessage: '',
configVersion: 1,
configTerm: 1
},
{
_id: 2,
name: '192.168.56.114:27016',
health: 1,
state: 7,
stateStr: 'ARBITER',
uptime: 24304,
syncSourceHost: '',
syncSourceId: -1,
infoMessage: '',
configVersion: 1,
configTerm: 1,
self: true,
lastHeartbeatMessage: ''
}
],
ok: 1
}
rs0 [direct: arbiter] test>
确认同步情况
rs.printSecondaryReplicationInfo()
D:\mongosh-2.6.0-win32-x64\bin>mongosh "mongodb://192.168.56.113:27013"
Current Mongosh Log ID: 698b4c9ea7994c5d08628c9f
Connecting to: mongodb://192.168.56.113:27013/?directConnection=true&appName=mongosh+2.6.0
Using MongoDB: 7.0.4
Using Mongosh: 2.6.0
For mongosh info see: https://www.mongodb.com/docs/mongodb-shell/
------
The server generated these startup warnings when booting
2026-02-10T16:29:31.285+08:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
------
rs0 [direct: secondary] test> rs.printSecondaryReplicationInfo()
source: 192.168.56.113:27013
{
syncedTo: 'Tue Feb 10 2026 23:22:41 GMT+0800 (中国标准时间)',
replLag: '0 secs (0 hrs) behind the primary '
}
rs0 [direct: secondary] test>
查看集群组成员
rs.conf().members
通过 rs.status() 查看当前副本集状态,找到members需要切换为Primary节点的数组下标,cfg.members[0] 中的 [0] 就是数组索引,表示第 1 个成员
rs0 [direct: primary] test> rs.conf().members
[
{
_id: 0,
host: '192.168.56.107:27017',
arbiterOnly: false,
buildIndexes: true,
hidden: false,
priority: 2,
tags: {},
secondaryDelaySecs: Long('0'),
votes: 1
},
{
_id: 1,
host: '192.168.56.113:27013',
arbiterOnly: false,
buildIndexes: true,
hidden: false,
priority: 1,
tags: {},
secondaryDelaySecs: Long('0'),
votes: 1
},
{
_id: 2,
host: '192.168.56.114:27016',
arbiterOnly: true,
buildIndexes: true,
hidden: false,
priority: 0,
tags: {},
secondaryDelaySecs: Long('0'),
votes: 1
}
]
主从切换测试
在主节点执行,修改节点的权重,权重大的为主,权重小的为从
config = rs.conf()
config.members[1].priority = 5
rs.reconfig(config)
说明:priority有效范围是 0--1000 的浮点数(含 0 和 1000),默认值 1。
mongodb中rs.reconfig(config)解释
底层调用的是 replSetReconfig 命令,只能在主节点上执行(除非加 {force:true})
rs0 [direct: primary] test> config = rs.conf() <<< 查看当前主从配置的priority
{
_id: 'rs0',
version: 1,
term: 3,
members: [
{
_id: 0,
host: '192.168.56.107:27017',
arbiterOnly: false,
buildIndexes: true,
hidden: false,
priority: 2,
tags: {},
secondaryDelaySecs: Long('0'),
votes: 1
},
{
_id: 1,
host: '192.168.56.113:27013',
arbiterOnly: false,
buildIndexes: true,
hidden: false,
priority: 1,
tags: {},
secondaryDelaySecs: Long('0'),
votes: 1
},
{
_id: 2,
host: '192.168.56.114:27016',
arbiterOnly: true,
buildIndexes: true,
hidden: false,
priority: 0,
tags: {},
secondaryDelaySecs: Long('0'),
votes: 1
}
],
protocolVersion: Long('1'),
writeConcernMajorityJournalDefault: true,
settings: {
chainingAllowed: true,
heartbeatIntervalMillis: 2000,
heartbeatTimeoutSecs: 10,
electionTimeoutMillis: 10000,
catchUpTimeoutMillis: -1,
catchUpTakeoverDelayMillis: 30000,
getLastErrorModes: {},
getLastErrorDefaults: { w: 1, wtimeout: 0 },
replicaSetId: ObjectId('698b3ac636c0e40ea3e5f66c')
}
}
rs0 [direct: primary] test> config.members[1].priority = 5 <<<<< 修改从库的priority节点大于当前主节点的priority
5
rs0 [direct: primary] test> rs.reconfig(config) <<<<< 刷新配置信息
{
ok: 1,
'$clusterTime': {
clusterTime: Timestamp({ t: 1770737382, i: 1 }),
signature: {
hash: Binary.createFromBase64('AAAAAAAAAAAAAAAAAAAAAAAAAAA=', 0),
keyId: Long('0')
}
},
operationTime: Timestamp({ t: 1770737382, i: 1 })
}
rs0 [direct: primary] test>
rs0 [direct: secondary] test> <<<<<<<<< 再次刷新原来的主库变成了从库
rs0 [direct: secondary] test>
原来的从库变成了主库
D:\mongosh-2.6.0-win32-x64\bin>mongosh "mongodb://192.168.56.113:27013"
Current Mongosh Log ID: 698b4f9be31ca9da01628c9f
Connecting to: mongodb://192.168.56.113:27013/?directConnection=true&appName=mongosh+2.6.0
Using MongoDB: 7.0.4
Using Mongosh: 2.6.0
For mongosh info see: https://www.mongodb.com/docs/mongodb-shell/
------
The server generated these startup warnings when booting
2026-02-10T16:29:31.285+08:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
------
rs0 [direct: primary] test>