Mongodb – Capturing mongo replica set state from mongo shell

mongodbscripting

I am trying to capture mongo replica set state from mongo shell. E.g.

[root@server ~]$ mongo
MongoDB shell version v3.6.8
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.6.8
rs0:SECONDARY>

I'd like to capture that SECONDARY keyword, and to do it in one command. I've tried something like mongo > output, however it requires a manual ctrl+c to terminate the process.

I have tried
parse rs.status() output to display one secondary node for mongodump destination

But the solution doesn't always work. Different mongo version can output different message. ARBITER node does not have authentication data either.

Best Answer

The output you are trying to capture is the default prompt for the mongo shell in interactive mode.

As at MongoDB 4.0 there isn't a built-in helper to return replica set member status as a string, but you can derive the same status in JavaScript.

For example, create the following as getstate.js:

    var mystate = 'UNKNOWN';

    // Note: isMaster command does not require authentication
    var isMaster = db.isMaster();

    if (isMaster.msg == "isdbgrid") {
        mystate = "mongos";
    } else if (isMaster.ismaster && !isMaster.setName) {
        mystate = 'STANDALONE';
    }

    if (isMaster.setName) {
        if (isMaster.secondary) {
            mystate = 'SECONDARY';
        } else if (isMaster.arbiterOnly) {
            mystate = "ARBITER";
        } else if (isMaster.primary === isMaster.me) {
            mystate = 'PRIMARY';
        }
    }

    print(mystate);

Now invoke mongo using --quiet to suppress any startup messages or warnings:

$ mongo localhost:27017 getstate.js --quiet
PRIMARY

$ mongo localhost:27018 getstate.js --quiet
SECONDARY

$ mongo localhost:27019 getstate.js --quiet
ARBITER