Hi Rohit
Although the mongos
process monitors the status of the replica set on each shard, I don’t believe there is a user-accessible method to extract this information from mongos
.
Instead of using rs.status()
, you might be able to use db.isMaster()
instead, which is a more lightweight command. You can also run the command without authentication, which avoids having to authenticate to run rs.status()
and keeping the connection open to avoid authentication cost.
Best regards
Kevin
Hi Rohit
It appears that the command connPoolStats does provide you with this information. You can run this command from a mongos
instance, and the shard’s primary would have the field ismaster: true
.
For example:
> db.runCommand({connPoolStats:1})
...
"replicaSets": {
"shard01": {
"hosts": [
{
"addr": "localhost:27018",
"ok": true,
"ismaster": true,
"hidden": false,
"secondary": false,
"pingTimeMillis": 0
},
{
"addr": "localhost:27019",
"ok": true,
"ismaster": false,
"hidden": false,
"secondary": true,
"pingTimeMillis": 0
},
{
"addr": "localhost:27020",
"ok": true,
"ismaster": false,
"hidden": false,
"secondary": true,
"pingTimeMillis": 0
}
]
},
"shard02": {
"hosts": [
{
"addr": "localhost:27021",
"ok": true,
"ismaster": true,
"hidden": false,
"secondary": false,
"pingTimeMillis": 0
},
{
"addr": "localhost:27022",
"ok": true,
"ismaster": false,
"hidden": false,
"secondary": true,
"pingTimeMillis": 0
},
{
"addr": "localhost:27023",
"ok": true,
"ismaster": false,
"hidden": false,
"secondary": true,
"pingTimeMillis": 0
}
]
},
...
From the example output above, the command shows that in shard01
the current primary is localhost:27018
, and in shard02
the current primary is localhost:27021
.
Best regards
Kevin
Hi Rohit
I believe you can use Javascript’s for..in statement to iterate through sub-documents. As an example, in a sharded cluster with 2 shards, 3 node replica set per shard, and a single node replica set as the config server:
connPool = db.runCommand({connPoolStats:1}).replicaSets;
for (var rs in connPool) {
print(rs);
replSet = connPool[rs].hosts;
for (var hs in replSet) {
print(' - ' + replSet[hs].addr + ' : ' + replSet[hs].ismaster);
}
}
Running this in the mongo
shell yields this output:
shard02
- localhost:27021 : true
- localhost:27022 : false
- localhost:27023 : false
configRepl
- localhost:27024 : true
shard01
- localhost:27018 : true
- localhost:27019 : false
- localhost:27020 : false
This shows that localhost:27018
is the primary of shard01
and localhost:27021
is the primary of shard02
. This was tested in the mongo
shell of MongoDB 3.6.5.
Best regards
Kevin