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
:Now invoke
mongo
using--quiet
to suppress any startup messages or warnings: