Attribute

ReadPreference (rp)

Purpose

Specifies a preference for the type of member (server node) of a replica set to which the driver attempts to connect. Connections to the primary member (read-write server nodes) return the most recent version of the data when executing Select queries, but increase the workload of the primary member and may negatively affect performance. To reduce the demand on the primary member, secondary members (read only server nodes) can be used at the expense of reading stale data.

Valid Values

0 | 1 | 2 | 3 | 4

Behavior

If set to 0 (None), the driver attempts to connect to only the member authorized by the application.

If set to 1 (Primary), the driver attempts to connect to only the primary member of a replica set. If the primary member is unavailable, the connection fails.

If set to 2 (PrimaryPreferred), the driver attempts to connect to the primary member first; but if it is unavailable, the driver attempts to connect to secondary members.

If set to 3 (Secondary), the driver attempts to connect to only secondary members of a replica set. If the secondary members of the replica set are unavailable, the connection fails.

If set to 4 (SecondaryPreferred), the driver attempts to connect to secondary members first; but if they are unavailable, the driver attempts to connect to the primary member.

Notes

  • When connected to secondary members (read-only) of a replica set, the driver will return an error when attempting to execute write operations. You can work around this limitation by providing a value for the Replica Set Name (ReplicaSetName) option to enable failover for write operations.

  • If the Read Preference option is configured to connect to a secondary member, the replica set that the driver is connecting to must contain a secondary member. If no secondary member exists, the driver will return an error.

  • This option only affects the member to which the driver connects and only during the connection process. For example, if you specified a value of secondary, the driver will not attempt to identify a new secondary member if the secondary member it is connected to is promoted to the primary member.

Default Value

1 (Primary)