Write operations for replica sets are performed exclusively through connections to the primary member. However, sometimes the primary member can become unavailable, for example, due to hardware failure or traffic overload. If this occurs, the other members elect a secondary member to assume the role of the primary. The ability to promote the secondary member during outages ensures uninterrupted availability of write operations and access to the most current version of data.

When replicate set failover is enabled, the driver handles this behavior by attempting to connect to the primary member for each write operation. If the connection fails, the driver repeats the discovery process until it finds the new primary member or the maximum number of retries have been attempted. You can enable replica set failover for write operations by specifying the name of your replica set using the ReplicaSetName property.

Note: When a value is specified for Replica Set Name, write operations will not fail when connected to secondary member for read operations. The driver will always attempt to connect to the primary member for write operations.

To configure replica set name failover for write operations:

  • Set ServerName to specify the name or the IP address of the MongoDB server to which you want to connect. For example, mymongodbserver.
  • Set DatabaseName to specify the name of the database to which you want to connect. This value is used as the default qualifier for unqualified table names in SQL queries. Required for User/ID password authentication.
  • Set PortNumber to specify the port number of the server listener. The default is 27017.
  • Set ReplicaSetName to specify the name of the replica set against which you want to execute write operations.

The following examples include the properties required for connecting with no authentication, replica set failover for write operations enabled, and replica set failover for read operations set to primary preferred .

Connection URL

jdbc:datadirect:mongodb://MongodbServer:27017;AuthenticationMethod=None;
     DatabaseName=Mongodb1;ReplicaSetName=MyReplicaSet

Data Source

MongoDBDataSource mds = new MongoDBSource();
mds.setDescription("My Replica Set Data Source");
mds.setAuthenticationMethod("None")
mds.setDatabaseName("Mongodb1");
mds.setPortNumber("27017");
mds.setReplicaSetName("MyReplicaSet");
mds.setServerName("MongodbServer");