Server Selector Example
Warning
Use of custom server selector functions is a power user feature. Misusing custom server selectors can have unintended consequences such as degraded read/write performance.
In this example, we write a server selector that prioritizes servers running on localhost
. This can be desirable when using a sharded cluster with multiple , as locally run queries are likely to see lower latency and higher throughput. Please note, however, that it is highly dependent on the application if preferring localhost
is beneficial or not.
In addition to comparing the hostname with localhost
, our server selector function accounts for the edge case when no servers are running on localhost
. In this case, we allow the default server selection logic to prevail by passing through the received server description list unchanged. Failure to do this would render the client unable to communicate with MongoDB in the event that no servers were running on .
Finally, we can create a MongoClient instance with this server selector.
>>> client = MongoClient(server_selector=server_selector)
Server Selection Process
This section dives deeper into the server selection process for reads and writes. In the case of a write, the driver performs the following operations (in order) during the selection process:
- Apply the user-defined server selector function. Note that the custom server selector is not called if there are no servers left from the previous filtering stage.
- Select a server at random from the remaining host list. The desired operation is then performed against the selected server.