HiveBrain v1.2.0
Get Started
← Back to all entries
snippetMinor

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

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
destinationnodemongodumpoutputstatusparsesecondaryonefordisplay

Problem

I wish to run mongodump to secondary (not primary). So I need as output hostname and port of one secondary.

# ./mongo  -udbadm admin --port 27100 -p --quiet --eval "printjson(rs.status().members.map(function(m) { return {'name':m.name, 'stateStr':m.stateStr} }))"
Enter password: 
[
        {
                "name" : "example-1.domain:27200",
                "stateStr" : "SECONDARY"
        },
        {
                "name" : "example-2.domain:27200",
                "stateStr" : "PRIMARY"
        },
        {
                "name" : "example-3.domain:27200",
                "stateStr" : "SECONDARY"
        }
]


With shell script tools is no problem for me to extract one secondary with hostname and port.
My question howto do this job the MongoDB way? What tools do you recommend me?
I heard that jq is better for JSON data. But don't know howto extract only one secondary host.

Solution

It's worth noting that if you pass in a replicaset string into mongodump it defaults to reading from a secondary from the set (note: in 3.0.5+ this is not the case if you connect to a mongos in a sharded cluster). If your replica set name was repl1 it would be something like:

./mongodump --host repl1/example-1.domain:27200,example-2.domain:27200


For reference, in the more recent versions (since the tools were re-written in Go), this is done by setting Monotonic mode when not connected to a mongos (source from 3.0.6 here).

To answer your specific question, a really simple way to parse rs.status() is with a filter, and it will fit on one line:

rs.status().members.filter(function(rsStatus) { return rsStatus.state === 2;})[0].name


That will return the name field of the first (hence [0]) secondary (state === 2) found in the array of members returned by rs.status()

Code Snippets

./mongodump --host repl1/example-1.domain:27200,example-2.domain:27200
rs.status().members.filter(function(rsStatus) { return rsStatus.state === 2;})[0].name

Context

StackExchange Database Administrators Q#114437, answer score: 5

Revisions (0)

No revisions yet.