Search code examples
databasemongodbreplicaset

How to get current member index in rs.conf() in MongoDB?


I am creating a Docker container with hidden secondary MongoDB instance for data backup purpose. The only way to configure a MongoDB instance as a hidden secondary I found, is after its start by getting rs.conf() and setting the corresponding member values of votes, priority, and hidden. However, I cannot automatically figure out what is the cluster member index of my current instance in the members array. Any ideas?

This is the script that needs to be executed, where 2 should be replaced with the current member index.

cfg = rs.conf()
cfg.members[2].priority = 0
cfg.members[2].votes = 0
cfg.members[2].hidden = true
rs.reconfig(cfg)

Solution

  • Something like this maybe:

    rso:PRIMARY> var myid=0;var x=0;var myself=db.isMaster().me ;rs.conf().members.forEach(function(d){ if(d.host==myself){ myid=x;print("The id is: "+myid)};x=x+1; })
    The id is: 2
    rso:PRIMARY> cfg.members[myid].priority=0
    

    Explained:

    1. Get the 'host:port' with the db.isMaster().me
    2. Loop over all conf().members and search which one is me
    3. Assign the myid to the member who is me.