MongoDB drivers use a Server Selection algorithm to choose which replica set member to use or, when connected to multiple mongos instances, which mongos instance to use.
Server selection occurs once per operation.
Note
Transactions that contain read operations must use read preference primary. All operations in a given transaction must route to the same member.
Read Preference for Replica Sets
Server selection occurs once per operation and is governed by the read preference and localThresholdMS settings to determine member eligibility for reads. The read preference is re-evaluated for each operation.
Read Preference Mode | Selection Process |
|---|---|
|
|
| |
| |
| |
|
Read Preference for Sharded Clusters
Load Balancing
If there is more than one mongos instance in the connection seed list, the driver determines which mongos is the "closest" (that is, the member with the lowest average network round-trip-time) and calculates the latency window by adding the average round-trip-time of this "closest" mongos instance and the localThresholdMS. The driver load balances randomly across the mongos instances that fall within the latency window.
Note
localThresholdMS biases server selection toward lower-latency local targets. The setting can't remove the cross-region network topology that a single private endpoint creates or guarantee all connections remain in the local region. In this configuration, a client can still connect through a mongos in another region.
Read Preference and Shards
For sharded clusters that have replica set shards, mongos applies the read preference when reading from the shards. Server selection is governed by the read preference and replication.localPingThresholdMs settings. The read preference is re-evaluated for each operation.
Read Preference Mode | Selection Process |
|---|---|
|
|
| |
| |
| |
| [1] | (1, 2) The default threshold value is 15 milliseconds. |