MongoDB 6.0.3副本集搭建

时间:2022-12-20 20:09:13

环境说明:

主:192.168.31.200 端口:27017
从:192.168.31.200 端口:27018
从:192.168.31.200 端口:27019

mongodb介质下载


上传

[root@dcs01 ~]# ls -lrth /soft/montodb/
total 69M
-rw-r--r-- 1 root root 69M Dec  9 16:51 mongodb-linux-x86_64-rhel70-6.0.3.tgz

检查MD5值

[root@dcs01 ~]# md5sum /soft/montodb/mongodb-linux-x86_64-rhel70-6.0.3.tgz 
39d04009f64a939c3c457a706738f0db  /soft/montodb/mongodb-linux-x86_64-rhel70-6.0.3.tgz

创建目录

mkdir /mongodb/{27017,27018,27019}/{dbms,data,log,conf} -p
[root@dcs01 ~]# tree /mongodb/
/mongodb/
├── 27017
│   ├── conf
│   ├── data
│   ├── dbms
│   └── log
├── 27018
│   ├── conf
│   ├── data
│   ├── dbms
│   └── log
└── 27019
    ├── conf
    ├── data
    ├── dbms
    └── log
15 directories, 0 files

解压

[root@cjc-db-01 montodb]# tar -zxvf mongodb-linux-x86_64-rhel70-6.0.3.tgz 
mongodb-linux-x86_64-rhel70-6.0.3/LICENSE-Community.txt
mongodb-linux-x86_64-rhel70-6.0.3/MPL-2
mongodb-linux-x86_64-rhel70-6.0.3/README
mongodb-linux-x86_64-rhel70-6.0.3/THIRD-PARTY-NOTICES
mongodb-linux-x86_64-rhel70-6.0.3/bin/install_compass
mongodb-linux-x86_64-rhel70-6.0.3/bin/mongod
mongodb-linux-x86_64-rhel70-6.0.3/bin/mongos

拷贝

[root@cjc-db-01 montodb]# cp -r mongodb-linux-x86_64-rhel70-6.0.3/* /mongodb/27017/dbms/
[root@cjc-db-01 montodb]# cp -r mongodb-linux-x86_64-rhel70-6.0.3/* /mongodb/27018/dbms/
[root@cjc-db-01 montodb]# cp -r mongodb-linux-x86_64-rhel70-6.0.3/* /mongodb/27019/dbms/

创建用户

[root@cjc-db-01 montodb]# useradd mongo
[root@cjc-db-01 montodb]# passwd mongo 
[root@cjc-db-01 montodb]# id mongo
uid=2002(mongo) gid=2002(mongo) groups=2002(mongo)

授权

[root@cjc-db-01 montodb]# chown mongo.mongo /mongodb -R

配置用户环境变量

[root@cjc-db-01 montodb]# su - mongo 
[mongo@cjc-db-01 ~]$ vi .bash_profile 
export MONGODB_HOME=/mongodb/27017/dbms/
#export MONGODB_HOME=/mongodb/27018/dbms/
#export MONGODB_HOME=/mongodb/27019/dbms/
export PATH=$PATH:$MONGODB_HOME/bin

准备配置文件

[mongo@cjc-db-01 ~]$ vi /mongodb/27017/conf/mongodb.conf
dbpath=/mongodb/27017/data
logpath=/mongodb/27017/log/mongodb.log
logappend=true
bind_ip = 0.0.0.0
fork = true
port = 27017

启动数据库

[mongo@cjc-db-01 ~]$ mongod -config /mongodb/27017/conf/mongodb.conf

登录数据库

没有mongo命令,需要下载mongoshell工具

[mongo@cjc-db-01 ~]$ mongo
bash: mongo: command not found...

下载mongoshell


[root@cjc-db-01 montodb]# ls -lrht mongosh-1.6.1-linux-x64.tgz 
-rw-r--r-- 1 root root 57M Dec  9 17:49 mongosh-1.6.1-linux-x64.tgz

检查md5值

[root@cjc-db-01 montodb]# md5sum mongosh-1.6.1-linux-x64.tgz 
8f66bb1f47531d9fc798af866c044bba  mongosh-1.6.1-linux-x64.tgz

解压

[root@cjc-db-01 montodb]# tar -zxvf mongosh-1.6.1-linux-x64.tgz 
[root@cjc-db-01 montodb]# mv mongosh-1.6.1-linux-x64/* /mongodb/mongosh/
[root@cjc-db-01 montodb]# chown mongo.mongo /mongodb -R

添加环境变量

[mongo@cjc-db-01 ~]$ vi .bash_profile 
export MONGODB_HOME=/mongodb/27017/dbms
export MONGOSH_HOME=/mongodb/mongosh
#export MONGODB_HOME=/mongodb/27018/dbms/
#export MONGODB_HOME=/mongodb/27019/dbms/
export PATH=$PATH:$MONGODB_HOME/bin:$MONGOSH_HOME/bin
[mongo@cjc-db-01 ~]$ source .bash_profile

再次登录数据库

mongosh "mongodb://ip:port"
mongosh ip:port/数据库  -u 用户名 -p 密码
mongosh -u 用户名 -p 密码 --port 端口号 --host ip 数据库名

[mongo@cjc-db-01 ~]$ ls /mongodb/mongosh/bin/
mongosh  mongosh_crypt_v1.so
[mongo@cjc-db-01 ~]$ vi .bash_profile 
[mongo@cjc-db-01 ~]$ source .bash_profile 
[mongo@cjc-db-01 ~]$ mongosh --port 27017
Current Mongosh Log ID:639305da87453024db5129bd
Connecting to:mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.6.1
Using MongoDB:6.0.3
Using Mongosh:1.6.1
For mongosh info see: 
To help improve our products, anonymous usage data is collected and sent to MongoDB periodically ().
You can opt-out by running the disableTelemetry() command.
------
   The server generated these startup warnings when booting
   2022-12-09T17:21:24.329+08:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
   2022-12-09T17:21:24.329+08:00: /sys/kernel/mm/transparent_hugepage/enabled is 'always'. We suggest setting it to 'never'
   2022-12-09T17:21:24.329+08:00: vm.max_map_count is too low
------
------
   Enable MongoDB's free cloud-based monitoring service, which will then receive and display
   metrics about your deployment (disk utilization, CPU, operation statistics, etc).
   
   The monitoring data will be available on a MongoDB website with a unique URL accessible to you
   and anyone you share the URL with. MongoDB may use this information to make product
   improvements and to suggest MongoDB products and deployment options to you.
   
   To enable free monitoring, run the following command: db.enableFreeMonitoring()
   To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
------
test> show dbs;
admin   40.00 KiB
config  12.00 KiB
local   40.00 KiB

插入测试数据

cjc> db.t01.insert({"tname":"cjc"})
DeprecationWarning: Collection.insert() is deprecated. Use insertOne, insertMany, or bulkWrite.
{
  acknowledged: true,
  insertedIds: { '0': ObjectId("6393063ca39bb9bd2b389670") }
}

cjc> db.t01.find()
[ { _id: ObjectId("6393063ca39bb9bd2b389670"), tname: 'cjc' } ]

关闭数据库

cjc> db.shutdownServer();
MongoNetworkError: connection 6 to 127.0.0.1:27017 closed

启动所有节点数据库

mongod -config /mongodb/27017/conf/mongodb.conf
mongod -config /mongodb/27018/conf/mongodb.conf
mongod -config /mongodb/27019/conf/mongodb.conf

查看进程

[mongo@cjc-db-01 mongodb]$ ps -ef|grep mongod|grep -v grep
mongo     2198     1  1 09:01 ?        00:00:07 mongod -config /mongodb/27017/conf/mongodb.conf
mongo     3158     1  6 09:12 ?        00:00:00 mongod -config /mongodb/27018/conf/mongodb.conf
mongo     3200     1  9 09:13 ?        00:00:00 mongod -config /mongodb/27019/conf/mongodb.conf

删除多余的数据库

test> use cjc
switched to db cjc
cjc> db.dropDatabase()
{ ok: 1, dropped: 'cjc' }

配置副本集

登录任一节点

mongosh --port 27017

配置副本集

配置文件添加参数

[mongo@cjc-db-01 ~]$ vi /mongodb/27017/conf/mongodb.conf 
[mongo@cjc-db-01 ~]$ vi /mongodb/27018/conf/mongodb.conf 
[mongo@cjc-db-01 ~]$ vi /mongodb/27019/conf/mongodb.conf 
replSet=cjcmonset

创建副本集

test> rs.initiate( {   _id : "cjcmonset",   members: [      { _id: 0, host: "192.168.31.200:27017" },      { _id: 1, host: "192.168.31.200:27018" },      { _id: 2, host: "192.168.31.200:27019" }   ]})

查看副本集配置

cjcmonset [direct: other] test> rs.conf()
{
  _id: 'cjcmonset',
  version: 1,
  term: 1,
  members: [
    {
      _id: 0,
      host: '192.168.31.200:27017',
      arbiterOnly: false,
      buildIndexes: true,
      hidden: false,
      priority: 1,
      tags: {},
      secondaryDelaySecs: Long("0"),
      votes: 1
    },
    {
      _id: 1,
      host: '192.168.31.200:27018',
      arbiterOnly: false,
      buildIndexes: true,
      hidden: false,
      priority: 1,
      tags: {},
      secondaryDelaySecs: Long("0"),
      votes: 1
    },
    {
      _id: 2,
      host: '192.168.31.200:27019',
      arbiterOnly: false,
      buildIndexes: true,
      hidden: false,
      priority: 1,
      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("63a111fd0e30878fbeca3b6b")
  }
}
cjcmonset [direct: primary] test>

查看副本集状态

cjcmonset [direct: primary] test> rs.status()
{
  set: 'cjcmonset',
  date: ISODate("2022-12-20T01:40:36.443Z"),
  myState: 1,
  term: Long("1"),
  syncSourceHost: '',
  syncSourceId: -1,
  heartbeatIntervalMillis: Long("2000"),
  majorityVoteCount: 2,
  writeMajorityCount: 2,
  votingMembersCount: 3,
  writableVotingMembersCount: 3,
  optimes: {
    lastCommittedOpTime: { ts: Timestamp({ t: 1671500427, i: 1 }), t: Long("1") },
    lastCommittedWallTime: ISODate("2022-12-20T01:40:27.265Z"),
    readConcernMajorityOpTime: { ts: Timestamp({ t: 1671500427, i: 1 }), t: Long("1") },
    appliedOpTime: { ts: Timestamp({ t: 1671500427, i: 1 }), t: Long("1") },
    durableOpTime: { ts: Timestamp({ t: 1671500427, i: 1 }), t: Long("1") },
    lastAppliedWallTime: ISODate("2022-12-20T01:40:27.265Z"),
    lastDurableWallTime: ISODate("2022-12-20T01:40:27.265Z")
  },
  lastStableRecoveryTimestamp: Timestamp({ t: 1671500397, i: 1 }),
  electionCandidateMetrics: {
    lastElectionReason: 'electionTimeout',
    lastElectionDate: ISODate("2022-12-20T01:38:16.879Z"),
    electionTerm: Long("1"),
    lastCommittedOpTimeAtElection: { ts: Timestamp({ t: 1671500285, i: 1 }), t: Long("-1") },
    lastSeenOpTimeAtElection: { ts: Timestamp({ t: 1671500285, i: 1 }), t: Long("-1") },
    numVotesNeeded: 2,
    priorityAtElection: 1,
    electionTimeoutMillis: Long("10000"),
    numCatchUpOps: Long("0"),
    newTermStartDate: ISODate("2022-12-20T01:38:17.119Z"),
    wMajorityWriteAvailabilityDate: ISODate("2022-12-20T01:38:18.561Z")
  },
  members: [
    {
      _id: 0,
      name: '192.168.31.200:27017',
      health: 1,
      state: 1,
      stateStr: 'PRIMARY',
      uptime: 792,
      optime: { ts: Timestamp({ t: 1671500427, i: 1 }), t: Long("1") },
      optimeDate: ISODate("2022-12-20T01:40:27.000Z"),
      lastAppliedWallTime: ISODate("2022-12-20T01:40:27.265Z"),
      lastDurableWallTime: ISODate("2022-12-20T01:40:27.265Z"),
      syncSourceHost: '',
      syncSourceId: -1,
      infoMessage: '',
      electionTime: Timestamp({ t: 1671500296, i: 1 }),
      electionDate: ISODate("2022-12-20T01:38:16.000Z"),
      configVersion: 1,
      configTerm: 1,
      self: true,
      lastHeartbeatMessage: ''
    },
    {
      _id: 1,
      name: '192.168.31.200:27018',
      health: 1,
      state: 2,
      stateStr: 'SECONDARY',
      uptime: 150,
      optime: { ts: Timestamp({ t: 1671500427, i: 1 }), t: Long("1") },
      optimeDurable: { ts: Timestamp({ t: 1671500427, i: 1 }), t: Long("1") },
      optimeDate: ISODate("2022-12-20T01:40:27.000Z"),
      optimeDurableDate: ISODate("2022-12-20T01:40:27.000Z"),
      lastAppliedWallTime: ISODate("2022-12-20T01:40:27.265Z"),
      lastDurableWallTime: ISODate("2022-12-20T01:40:27.265Z"),
      lastHeartbeat: ISODate("2022-12-20T01:40:35.270Z"),
      lastHeartbeatRecv: ISODate("2022-12-20T01:40:34.639Z"),
      pingMs: Long("0"),
      lastHeartbeatMessage: '',
      syncSourceHost: '192.168.31.200:27017',
      syncSourceId: 0,
      infoMessage: '',
      configVersion: 1,
      configTerm: 1
    },
    {
      _id: 2,
      name: '192.168.31.200:27019',
      health: 1,
      state: 2,
      stateStr: 'SECONDARY',
      uptime: 150,
      optime: { ts: Timestamp({ t: 1671500427, i: 1 }), t: Long("1") },
      optimeDurable: { ts: Timestamp({ t: 1671500427, i: 1 }), t: Long("1") },
      optimeDate: ISODate("2022-12-20T01:40:27.000Z"),
      optimeDurableDate: ISODate("2022-12-20T01:40:27.000Z"),
      lastAppliedWallTime: ISODate("2022-12-20T01:40:27.265Z"),
      lastDurableWallTime: ISODate("2022-12-20T01:40:27.265Z"),
      lastHeartbeat: ISODate("2022-12-20T01:40:35.267Z"),
      lastHeartbeatRecv: ISODate("2022-12-20T01:40:34.638Z"),
      pingMs: Long("0"),
      lastHeartbeatMessage: '',
      syncSourceHost: '192.168.31.200:27017',
      syncSourceId: 0,
      infoMessage: '',
      configVersion: 1,
      configTerm: 1
    }
  ],
  ok: 1,
  '$clusterTime': {
    clusterTime: Timestamp({ t: 1671500427, i: 1 }),
    signature: {
      hash: Binary(Buffer.from("0000000000000000000000000000000000000000", "hex"), 0),
      keyId: Long("0")
    }
  },
  operationTime: Timestamp({ t: 1671500427, i: 1 })
}

数据写入测试

cjcmonset [direct: primary] test> use cjc
cjc> db.t01.insert({"tname":"cjc"})
cjc> db.t01.find()

查看其他节点

[mongo@cjc-db-01 mongodb]$ mongosh --port 27018
cjcmonset [direct: secondary] test> use cjc
switched to db cjc
cjcmonset [direct: secondary] cjc> db.t01.find()
MongoServerError: not primary and secondaryOk=false - consider using db.getMongo().setReadPref() or readPreference in the connection string

[mongo@cjc-db-01 mongodb]$ mongosh --port 27019
cjcmonset [direct: secondary] cjc> db.t01.find()
MongoServerError: not primary and secondaryOk=false - consider using db.getMongo().setReadPref() or readPreference in the connection string

cjcmonset [direct: secondary] cjc> db.getMongo().setSlaveOk();
MongoshDeprecatedError: [COMMON-10003] Setting slaveOk is deprecated, use setReadPref instead.

设置副本集可以从secondary读取数据

cjcmonset [direct: secondary] cjc> db.getMongo().setReadPref("secondary")
cjcmonset [direct: secondary] cjc> db.t01.find()
[ { _id: ObjectId("63a113836be69aceb7e1ae9b"), tname: 'cjc' } ]

主从切换

登录主库

[mongo@cjc-db-01 mongodb]$ mongosh --port 27017

停主库

cjcmonset [direct: primary] test> db.shutdownServer();
MongoNetworkError: connection 1 to 127.0.0.1:27017 closed

检查当前主库

可以看到原主库27017故障后,primary切换到27018节点。

[mongo@cjc-db-01 mongodb]$ mongosh --port 27018
cjcmonset [direct: primary] test> rs.status();
{
  set: 'cjcmonset',
  date: ISODate("2022-12-20T02:15:33.806Z"),
  myState: 1,
  term: Long("2"),
  syncSourceHost: '',
  syncSourceId: -1,
  heartbeatIntervalMillis: Long("2000"),
  majorityVoteCount: 2,
  writeMajorityCount: 2,
  votingMembersCount: 3,
  writableVotingMembersCount: 3,
  optimes: {
    lastCommittedOpTime: { ts: Timestamp({ t: 1671502526, i: 1 }), t: Long("2") },
    lastCommittedWallTime: ISODate("2022-12-20T02:15:26.248Z"),
    readConcernMajorityOpTime: { ts: Timestamp({ t: 1671502526, i: 1 }), t: Long("2") },
    appliedOpTime: { ts: Timestamp({ t: 1671502526, i: 1 }), t: Long("2") },
    durableOpTime: { ts: Timestamp({ t: 1671502526, i: 1 }), t: Long("2") },
    lastAppliedWallTime: ISODate("2022-12-20T02:15:26.248Z"),
    lastDurableWallTime: ISODate("2022-12-20T02:15:26.248Z")
  },
  lastStableRecoveryTimestamp: Timestamp({ t: 1671502516, i: 1 }),
  electionCandidateMetrics: {
    lastElectionReason: 'stepUpRequestSkipDryRun',
    lastElectionDate: ISODate("2022-12-20T02:14:36.145Z"),
    electionTerm: Long("2"),
    lastCommittedOpTimeAtElection: { ts: Timestamp({ t: 1671502467, i: 1 }), t: Long("1") },
    lastSeenOpTimeAtElection: { ts: Timestamp({ t: 1671502467, i: 1 }), t: Long("1") },
    numVotesNeeded: 2,
    priorityAtElection: 1,
    electionTimeoutMillis: Long("10000"),
    priorPrimaryMemberId: 0,
    numCatchUpOps: Long("0"),
    newTermStartDate: ISODate("2022-12-20T02:14:36.240Z"),
    wMajorityWriteAvailabilityDate: ISODate("2022-12-20T02:14:37.176Z")
  },
  electionParticipantMetrics: {
    votedForCandidate: true,
    electionTerm: Long("1"),
    lastVoteDate: ISODate("2022-12-20T01:38:16.912Z"),
    electionCandidateMemberId: 0,
    voteReason: '',
    lastAppliedOpTimeAtElection: { ts: Timestamp({ t: 1671500285, i: 1 }), t: Long("-1") },
    maxAppliedOpTimeInSet: { ts: Timestamp({ t: 1671500285, i: 1 }), t: Long("-1") },
    priorityAtElection: 1
  },
  members: [
    {
      _id: 0,
      name: '192.168.31.200:27017',
      health: 0,
      state: 8,
      stateStr: '(not reachable/healthy)',
      uptime: 0,
      optime: { ts: Timestamp({ t: 0, i: 0 }), t: Long("-1") },
      optimeDurable: { ts: Timestamp({ t: 0, i: 0 }), t: Long("-1") },
      optimeDate: ISODate("1970-01-01T00:00:00.000Z"),
      optimeDurableDate: ISODate("1970-01-01T00:00:00.000Z"),
      lastAppliedWallTime: ISODate("2022-12-20T02:14:46.243Z"),
      lastDurableWallTime: ISODate("2022-12-20T02:14:46.243Z"),
      lastHeartbeat: ISODate("2022-12-20T02:15:32.419Z"),
      lastHeartbeatRecv: ISODate("2022-12-20T02:14:49.286Z"),
      pingMs: Long("0"),
      lastHeartbeatMessage: 'Error connecting to 192.168.31.200:27017 :: caused by :: Connection refused',
      syncSourceHost: '',
      syncSourceId: -1,
      infoMessage: '',
      configVersion: 1,
      configTerm: 1
    },
    {
      _id: 1,
      name: '192.168.31.200:27018',
      health: 1,
      state: 1,
      stateStr: 'PRIMARY',
      uptime: 2883,
      optime: { ts: Timestamp({ t: 1671502526, i: 1 }), t: Long("2") },
      optimeDate: ISODate("2022-12-20T02:15:26.000Z"),
      lastAppliedWallTime: ISODate("2022-12-20T02:15:26.248Z"),
      lastDurableWallTime: ISODate("2022-12-20T02:15:26.248Z"),
      syncSourceHost: '',
      syncSourceId: -1,
      infoMessage: '',
      electionTime: Timestamp({ t: 1671502476, i: 1 }),
      electionDate: ISODate("2022-12-20T02:14:36.000Z"),
      configVersion: 1,
      configTerm: 2,
      self: true,
      lastHeartbeatMessage: ''
    },
    {
      _id: 2,
      name: '192.168.31.200:27019',
      health: 1,
      state: 2,
      stateStr: 'SECONDARY',
      uptime: 2247,
      optime: { ts: Timestamp({ t: 1671502526, i: 1 }), t: Long("2") },
      optimeDurable: { ts: Timestamp({ t: 1671502526, i: 1 }), t: Long("2") },
      optimeDate: ISODate("2022-12-20T02:15:26.000Z"),
      optimeDurableDate: ISODate("2022-12-20T02:15:26.000Z"),
      lastAppliedWallTime: ISODate("2022-12-20T02:15:26.248Z"),
      lastDurableWallTime: ISODate("2022-12-20T02:15:26.248Z"),
      lastHeartbeat: ISODate("2022-12-20T02:15:32.305Z"),
      lastHeartbeatRecv: ISODate("2022-12-20T02:15:33.355Z"),
      pingMs: Long("0"),
      lastHeartbeatMessage: '',
      syncSourceHost: '192.168.31.200:27018',
      syncSourceId: 1,
      infoMessage: '',
      configVersion: 1,
      configTerm: 2
    }
  ],
  ok: 1,
  '$clusterTime': {
    clusterTime: Timestamp({ t: 1671502526, i: 1 }),
    signature: {
      hash: Binary(Buffer.from("0000000000000000000000000000000000000000", "hex"), 0),
      keyId: Long("0")
    }
  },
  operationTime: Timestamp({ t: 1671502526, i: 1 })
}
cjcmonset [direct: primary] test>

新增测试数据

cjc> db.t01.insert({"txx":"abc"})
cjcmonset [direct: primary] cjc> db.t01.find()
[
  { _id: ObjectId("63a113836be69aceb7e1ae9b"), tname: 'cjc' },
  { _id: ObjectId("63a1217973fc637ac59b96f0"), txx: 'abc' }
]

继续停主库

[mongo@cjc-db-01 mongodb]$ mongosh --port 27018
cjcmonset [direct: primary] test> db.shutdownServer();

[mongo@cjc-db-01 mongodb]$ mongosh --port 27019
cjcmonset [direct: secondary] test> rs.status()
{
  set: 'cjcmonset',
  date: ISODate("2022-12-20T03:01:49.481Z"),
  myState: 2,
  term: Long("3"),
  syncSourceHost: '',
  syncSourceId: -1,
  heartbeatIntervalMillis: Long("2000"),
  majorityVoteCount: 2,
  writeMajorityCount: 2,
  votingMembersCount: 3,
  writableVotingMembersCount: 3,
  optimes: {
    lastCommittedOpTime: { ts: Timestamp({ t: 1671504345, i: 1 }), t: Long("3") },
    lastCommittedWallTime: ISODate("2022-12-20T02:45:45.661Z"),
    readConcernMajorityOpTime: { ts: Timestamp({ t: 1671504345, i: 1 }), t: Long("3") },
    appliedOpTime: { ts: Timestamp({ t: 1671504355, i: 1 }), t: Long("3") },
    durableOpTime: { ts: Timestamp({ t: 1671504355, i: 1 }), t: Long("3") },
    lastAppliedWallTime: ISODate("2022-12-20T02:45:55.661Z"),
    lastDurableWallTime: ISODate("2022-12-20T02:45:55.661Z")
  },
  lastStableRecoveryTimestamp: Timestamp({ t: 1671504345, i: 1 }),
  electionParticipantMetrics: {
    votedForCandidate: true,
    electionTerm: Long("2"),
    lastVoteDate: ISODate("2022-12-20T02:14:36.224Z"),
    electionCandidateMemberId: 1,
    voteReason: '',
    lastAppliedOpTimeAtElection: { ts: Timestamp({ t: 1671502467, i: 1 }), t: Long("1") },
    maxAppliedOpTimeInSet: { ts: Timestamp({ t: 1671502467, i: 1 }), t: Long("1") },
    priorityAtElection: 1
  },
  members: [
    {
      _id: 0,
      name: '192.168.31.200:27017',
      health: 0,
      state: 8,
      stateStr: '(not reachable/healthy)',
      uptime: 0,
      optime: { ts: Timestamp({ t: 0, i: 0 }), t: Long("-1") },
      optimeDurable: { ts: Timestamp({ t: 0, i: 0 }), t: Long("-1") },
      optimeDate: ISODate("1970-01-01T00:00:00.000Z"),
      optimeDurableDate: ISODate("1970-01-01T00:00:00.000Z"),
      lastAppliedWallTime: ISODate("2022-12-20T02:14:46.243Z"),
      lastDurableWallTime: ISODate("2022-12-20T02:14:46.243Z"),
      lastHeartbeat: ISODate("2022-12-20T03:01:49.143Z"),
      lastHeartbeatRecv: ISODate("2022-12-20T02:14:49.286Z"),
      pingMs: Long("0"),
      lastHeartbeatMessage: 'Error connecting to 192.168.31.200:27017 :: caused by :: Connection refused',
      syncSourceHost: '',
      syncSourceId: -1,
      infoMessage: '',
      configVersion: 1,
      configTerm: 2
    },
    {
      _id: 1,
      name: '192.168.31.200:27018',
      health: 0,
      state: 8,
      stateStr: '(not reachable/healthy)',
      uptime: 0,
      optime: { ts: Timestamp({ t: 0, i: 0 }), t: Long("-1") },
      optimeDurable: { ts: Timestamp({ t: 0, i: 0 }), t: Long("-1") },
      optimeDate: ISODate("1970-01-01T00:00:00.000Z"),
      optimeDurableDate: ISODate("1970-01-01T00:00:00.000Z"),
      lastAppliedWallTime: ISODate("2022-12-20T02:45:45.661Z"),
      lastDurableWallTime: ISODate("2022-12-20T02:45:45.661Z"),
      lastHeartbeat: ISODate("2022-12-20T03:01:49.143Z"),
      lastHeartbeatRecv: ISODate("2022-12-20T02:45:48.697Z"),
      pingMs: Long("0"),
      lastHeartbeatMessage: 'Error connecting to 192.168.31.200:27018 :: caused by :: Connection refused',
      syncSourceHost: '',
      syncSourceId: -1,
      infoMessage: '',
      configVersion: 1,
      configTerm: 3
    },
    {
      _id: 2,
      name: '192.168.31.200:27019',
      health: 1,
      state: 2,
      stateStr: 'SECONDARY',
      uptime: 5653,
      optime: { ts: Timestamp({ t: 1671504355, i: 1 }), t: Long("3") },
      optimeDate: ISODate("2022-12-20T02:45:55.000Z"),
      lastAppliedWallTime: ISODate("2022-12-20T02:45:55.661Z"),
      lastDurableWallTime: ISODate("2022-12-20T02:45:55.661Z"),
      syncSourceHost: '',
      syncSourceId: -1,
      infoMessage: 'Could not find member to sync from',
      configVersion: 1,
      configTerm: 3,
      self: true,
      lastHeartbeatMessage: ''
    }
  ],
  ok: 1,
  '$clusterTime': {
    clusterTime: Timestamp({ t: 1671504355, i: 1 }),
    signature: {
      hash: Binary(Buffer.from("0000000000000000000000000000000000000000", "hex"), 0),
      keyId: Long("0")
    }
  },
  operationTime: Timestamp({ t: 1671504355, i: 1 })
}
cjcmonset [direct: secondary] test>

插入数据

cjcmonset [direct: secondary] test> use cjc
switched to db cjc
cjcmonset [direct: secondary] cjc> db.t01.insert({"aaa":"ccc"})
DeprecationWarning: Collection.insert() is deprecated. Use insertOne, insertMany, or bulkWrite.
Uncaught:
MongoBulkWriteError: not primary
Result: BulkWriteResult {
  result: {
    ok: 1,
    writeErrors: [],
    writeConcernErrors: [],
    insertedIds: [ { index: 0, _id: ObjectId("63a126025f708e296b832629") } ],
    nInserted: 0,
    nUpserted: 0,
    nMatched: 0,
    nModified: 0,
    nRemoved: 0,
    upserted: []
  }
}

查看

cjcmonset [direct: secondary] cjc> db.getMongo().setReadPref("secondary")
cjcmonset [direct: secondary] cjc> db.t01.find()
[
  { _id: ObjectId("63a113836be69aceb7e1ae9b"), tname: 'cjc' },
  { _id: ObjectId("63a1217973fc637ac59b96f0"), txx: 'abc' }
]

启动

[mongo@cjc-db-01 mongodb]$ mongod -config /mongodb/27017/conf/mongodb.conf
[mongo@cjc-db-01 mongodb]$ mongod -config /mongodb/27018/conf/mongodb.conf

27019变成新主库

[mongo@cjc-db-01 mongodb]$ mongosh --port 27019
cjcmonset [direct: primary] test> rs.status();
{
  set: 'cjcmonset',
  date: ISODate("2022-12-20T03:06:08.740Z"),
  myState: 1,
  term: Long("4"),
  syncSourceHost: '',
  syncSourceId: -1,
  heartbeatIntervalMillis: Long("2000"),
  majorityVoteCount: 2,
  writeMajorityCount: 2,
  votingMembersCount: 3,
  writableVotingMembersCount: 3,
  optimes: {
    lastCommittedOpTime: { ts: Timestamp({ t: 1671505563, i: 1 }), t: Long("4") },
    lastCommittedWallTime: ISODate("2022-12-20T03:06:03.084Z"),
    readConcernMajorityOpTime: { ts: Timestamp({ t: 1671505563, i: 1 }), t: Long("4") },
    appliedOpTime: { ts: Timestamp({ t: 1671505563, i: 1 }), t: Long("4") },
    durableOpTime: { ts: Timestamp({ t: 1671505563, i: 1 }), t: Long("4") },
    lastAppliedWallTime: ISODate("2022-12-20T03:06:03.084Z"),
    lastDurableWallTime: ISODate("2022-12-20T03:06:03.084Z")
  },
  lastStableRecoveryTimestamp: Timestamp({ t: 1671505523, i: 1 }),
  electionCandidateMetrics: {
    lastElectionReason: 'electionTimeout',
    lastElectionDate: ISODate("2022-12-20T03:04:53.017Z"),
    electionTerm: Long("4"),
    lastCommittedOpTimeAtElection: { ts: Timestamp({ t: 1671504345, i: 1 }), t: Long("3") },
    lastSeenOpTimeAtElection: { ts: Timestamp({ t: 1671504355, i: 1 }), t: Long("3") },
    numVotesNeeded: 2,
    priorityAtElection: 1,
    electionTimeoutMillis: Long("10000"),
    numCatchUpOps: Long("0"),
    newTermStartDate: ISODate("2022-12-20T03:04:53.059Z"),
    wMajorityWriteAvailabilityDate: ISODate("2022-12-20T03:04:53.679Z")
  },
  electionParticipantMetrics: {
    votedForCandidate: true,
    electionTerm: Long("2"),
    lastVoteDate: ISODate("2022-12-20T02:14:36.224Z"),
    electionCandidateMemberId: 1,
    voteReason: '',
    lastAppliedOpTimeAtElection: { ts: Timestamp({ t: 1671502467, i: 1 }), t: Long("1") },
    maxAppliedOpTimeInSet: { ts: Timestamp({ t: 1671502467, i: 1 }), t: Long("1") },
    priorityAtElection: 1
  },
  members: [
    {
      _id: 0,
      name: '192.168.31.200:27017',
      health: 1,
      state: 2,
      stateStr: 'SECONDARY',
      uptime: 81,
      optime: { ts: Timestamp({ t: 1671505563, i: 1 }), t: Long("4") },
      optimeDurable: { ts: Timestamp({ t: 1671505563, i: 1 }), t: Long("4") },
      optimeDate: ISODate("2022-12-20T03:06:03.000Z"),
      optimeDurableDate: ISODate("2022-12-20T03:06:03.000Z"),
      lastAppliedWallTime: ISODate("2022-12-20T03:06:03.084Z"),
      lastDurableWallTime: ISODate("2022-12-20T03:06:03.084Z"),
      lastHeartbeat: ISODate("2022-12-20T03:06:07.159Z"),
      lastHeartbeatRecv: ISODate("2022-12-20T03:06:08.167Z"),
      pingMs: Long("0"),
      lastHeartbeatMessage: '',
      syncSourceHost: '192.168.31.200:27019',
      syncSourceId: 2,
      infoMessage: '',
      configVersion: 1,
      configTerm: 4
    },
    {
      _id: 1,
      name: '192.168.31.200:27018',
      health: 1,
      state: 2,
      stateStr: 'SECONDARY',
      uptime: 76,
      optime: { ts: Timestamp({ t: 1671505563, i: 1 }), t: Long("4") },
      optimeDurable: { ts: Timestamp({ t: 1671505563, i: 1 }), t: Long("4") },
      optimeDate: ISODate("2022-12-20T03:06:03.000Z"),
      optimeDurableDate: ISODate("2022-12-20T03:06:03.000Z"),
      lastAppliedWallTime: ISODate("2022-12-20T03:06:03.084Z"),
      lastDurableWallTime: ISODate("2022-12-20T03:06:03.084Z"),
      lastHeartbeat: ISODate("2022-12-20T03:06:07.159Z"),
      lastHeartbeatRecv: ISODate("2022-12-20T03:06:08.166Z"),
      pingMs: Long("0"),
      lastHeartbeatMessage: '',
      syncSourceHost: '192.168.31.200:27019',
      syncSourceId: 2,
      infoMessage: '',
      configVersion: 1,
      configTerm: 4
    },
    {
      _id: 2,
      name: '192.168.31.200:27019',
      health: 1,
      state: 1,
      stateStr: 'PRIMARY',
      uptime: 5912,
      optime: { ts: Timestamp({ t: 1671505563, i: 1 }), t: Long("4") },
      optimeDate: ISODate("2022-12-20T03:06:03.000Z"),
      lastAppliedWallTime: ISODate("2022-12-20T03:06:03.084Z"),
      lastDurableWallTime: ISODate("2022-12-20T03:06:03.084Z"),
      syncSourceHost: '',
      syncSourceId: -1,
      infoMessage: '',
      electionTime: Timestamp({ t: 1671505493, i: 1 }),
      electionDate: ISODate("2022-12-20T03:04:53.000Z"),
      configVersion: 1,
      configTerm: 4,
      self: true,
      lastHeartbeatMessage: ''
    }
  ],
  ok: 1,
  '$clusterTime': {
    clusterTime: Timestamp({ t: 1671505563, i: 1 }),
    signature: {
      hash: Binary(Buffer.from("0000000000000000000000000000000000000000", "hex"), 0),
      keyId: Long("0")
    }
  },
  operationTime: Timestamp({ t: 1671505563, i: 1 })
}
cjcmonset [direct: primary] test>

插入数据测试

cjcmonset [direct: primary] cjc> db.t01.insert({"aaa":"ccc"})
DeprecationWarning: Collection.insert() is deprecated. Use insertOne, insertMany, or bulkWrite.
{
  acknowledged: true,
  insertedIds: { '0': ObjectId("63a126e5406e8620614e4fd5") }
}
cjcmonset [direct: primary] cjc> db.t01.find()
[
  { _id: ObjectId("63a113836be69aceb7e1ae9b"), tname: 'cjc' },
  { _id: ObjectId("63a1217973fc637ac59b96f0"), txx: 'abc' },
  { _id: ObjectId("63a126e5406e8620614e4fd5"), aaa: 'ccc' }
]

查看数据库版本

cjcmonset [direct: primary] admin> db.version()
6.0.3

查看帮助信息

cjcmonset [direct: primary] admin> rs.help()
  Replica Set Class:
    initiate                                   Initiates the replica set.
    config                                     Returns a document that contains the current replica set configuration.
    conf                                       Calls replSetConfig
    reconfig                                   Reconfigures an existing replica set, overwriting the existing replica set configuration.
    reconfigForPSASet                          Reconfigures an existing replica set, overwriting the existing replica set configuration, if the reconfiguration is a transition from a Primary-Arbiter to a Primary-Secondary-Arbiter set.
    status                                     Calls replSetGetStatus
    isMaster                                   Calls isMaster
    hello                                      Calls hello
    printSecondaryReplicationInfo              Calls db.printSecondaryReplicationInfo
    printSlaveReplicationInfo                  DEPRECATED. Use rs.printSecondaryReplicationInfo
    printReplicationInfo                       Calls db.printReplicationInfo
    add                                        Adds replica set member to replica set.
    addArb                                     Calls rs.add with arbiterOnly=true
    remove                                     Removes a replica set member.
    freeze                                     Prevents the current member from seeking election as primary for a period of time. Uses the replSetFreeze command
    stepDown                                   Causes the current primary to become a secondary which forces an election. If no stepDownSecs is provided, uses 60 seconds. Uses the replSetStepDown command
    syncFrom                                   Sets the member that this replica set member will sync from, overriding the default sync target selection logic.
    secondaryOk                                This method is deprecated. Use db.getMongo().setReadPref() instead
  For more information on usage: 

###chenjuchao 20221220 14:30###