Search code examples
mongodbaggregationsubstrreplicaset

How to use substr on rs.status() of mongodb to get hostname only


I'd like to retrieve all host names without port number using rs.status() in MongoDB replica set. I tried below one but it is not giving the required output.

MongoDB Enterprise rsMDB001P:PRIMARY> print([{ $substr: ["$rs.status().members[0].name", 0, 13]}])

[object Object]

Can someone correct my syntax to get required output.


Solution

  • Try this one:

    rs.status().members.forEach(function (m) { print(m.name.split(":").shift()) }) 
    

    If you like to skip also the host domain, then use

    rs.status().members.forEach(function (m) { print(m.name.split(":").shift().split(".").shift()) })