Re-selecting the same primary

The instructor shows how the he kills the primary server in a 3-server replica set. And then restarts it. Automatically, that server again assumes the primary.
This doesn’t happen for me. If I kill primary on, say, port 27001, then restart it, then say
mongo --port 27001
I end up connecting to secondary. I do rs.status() and find out that now 27003 is primary. I can disconnect and connect to 27003, of course. But in production environment, this may not fly.
So, how do I ensure, that as soon as 27001 goes back online, it becomes primary?
Thanks.

@Vicky_B it actually doesn’t matter which node becomes primary in the eyes of mongo. What’s crucial is the way you connect. Include the name of the replica set and two or more nodes and you will automatically be connected to the primary. This how you will connect in prod:
mongo --host "replica_set_name/node_1:port,node_2:port,etc..."

Or you can use SRV if it’s setup. With SRV you won’t need to include all the nodes.

However, to answer your question, if you want to force a specific node to become primary, all you do is change the priority property of that node to a higher value than other secondaries.

1 Like

This how you will connect in prod:
mongo --host "replica_set_name/node_1:port,node_2:port,etc..."

this is brilliant. thanks!

all you do is change the priority property of that node to a higher value than other secondaries

somehow, it never worked for me. MongoDB seems to ignore it. Or am I doing it in wrong time? After the replica set is fired up and I am connected to it via mongo, it seems too late. If you have a chance to give line-by-line, that would be awesome.

Sure! Basically, you take a copy of the config doc, make your changes and reconfigure the replica set using the new doc. You can change so many other properties this way too:

var cfg = rs.conf()
cfg.members[0].priority = 1
cfg.members[1].priority = 0.5
cfg.members[2].priority = 0.5
rs.reconfig(cfg)

NB: The index is not the same as the _id property. It’s actually the index of the doc, so check it beforehand.

Re conn strings, you might find these useful:
https://docs.mongodb.com/manual/reference/connection-string/

cfg.members[0].priority

the code you wrote, when exactly do I run it?

I used to go
mongo --port [port of primary server]
use admin
db.auth(‘some_admin_acc’, ‘blah_blah’)

and then the piece you wrote. Zero effect.

UPDATE
when I connected the way you described in earlier reply ("mongo --host “replica_st_name/node 1…”), it worked!
so, how I connected to primary, made all the difference.

Just want to say thank you to @007_jb again. I’ve been struggling with this for weeks.

No problem! You’re welcome!

It’s a config setting so it has already been set. It will kick in when an election of a primary node is started or when you do a rolling upgrade. Let’s see the output of rs.config().members