I can't connect to a new master node in ReplicaSet

Hi @Kaper_N_A and welcome in the MongoDB Community :muscle: !

  1. What does the hosts variable contains?
  2. No routing/firewall issues? You can connect to all the nodes from the server that executes the python code?
  3. Why are you using 2 different clients client and masterClient here? Looks like you just want to change the readPreference parameter which can be overloaded at the “level” you want. A new readPreference at the database level will overwrite the readPreference defined at the client level, etc. query > collection > database > client to keep it simple.
  4. w, i.e the writeConcern should NEVER be equal to len(hosts.split(',')). If you have 3 nodes, it means that w=3… So it means that as soon as one of your node starts to fail (or you are doing a maintenance operation like an upgrade or daily backup), you cannot acknowledge any write operation on your entire cluster as you cannot write to 3 nodes anymore. That’s not really “Highly Available”. That’s the first FIRST reason for replica set to exist. They provide HA. By doing this, you break this principal and increased your chances of failure compared to running on a single server.
  5. Did this error just last for the time of the election process or did it persisted after the new Primary was elected? If this just happened during the election process, it’s expected as you cannot write to a cluster that doesn’t have a primary… BUT you could have been saved by the automatic retryWrites. Maybe you are actually using it already, by default. But it depends which versions you are running. CF the doc for this.
  6. What’s your serverSelectionTimeoutMS? Looks like your election took longer than your serverSelectionTimeoutMS to find a new Primary. Maybe you could increase it or resolve the issue(s) that prevent your cluster from electing a new Primary in a timely manner.

That’s all the idea & comments I have for now :smiley:.
I hope this will help a bit.

Cheers,
Maxime.