0

If I've to get something like analogous to SQL statement from rs.status output to print specific value of an attribute in mongoDB -

Something like print health of specific node of a replica set from rs.status.

select health from rs.status where hostname like 'abc:123'

or something to print lagtime of a specific secondary replica node with respect to Primary node using :

print lagtime from rs.printSlaveReplicationInfo() where hostname like 'abc:123'

what would be the simple query or JS to run against a replica set connection string ?

2
  • Simply rs.printSlaveReplicationInfo() Jul 19 at 12:12
  • but instead of printing everything with command rs.printSlaveReplicationInfo(). I would like to capture only specific key value like for health either 1 or 0 and assign that value to a variable in Linux shell. Is there any simplest way.
    – unknown
    Jul 19 at 16:04
2

A one-liner would be this one:

mongo "mongodb://username:password@localhost:27018/admin?authSource=admin" --quiet --norc --eval "rs.status().members.filter( x => x.name == db.hello().me ).shift().health"

Function db.hello().me returns the server+port you are currently connected to. Replace this expression if you like to query other server in this replica set.

4
  • Getting an error : db.hello() 2021-07-20T04:49:24.093+0000 E QUERY [js] TypeError: db.hello is not a function :
    – unknown
    Jul 20 at 4:51
  • db.hello() New in version 5.0: (and 4.4.2, 4.2.10, 4.0.21, and 3.6.21). As per - docs.mongodb.com/manual/reference/method/db.hello
    – unknown
    Jul 20 at 4:57
  • If you use an older mongoDB version try db.hostInfo().system.hostname Jul 20 at 5:48
  • db.hostInfo().system.hostname works for me.
    – unknown
    Jul 20 at 9:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.