JDBC Driver for MongoDB

Build 22.0.8462

ReadPreference

Set this to a strategy for reading from a replica set. Accepted values are primary, primaryPreferred, secondary, secondaryPreferred, and nearest.

Data Type

string

Default Value

"primary"

Remarks

This property enables you to execute queries to a member in a replica set other other than the primary member. Accepted values are the following:

  • primary: All SELECT queries are executed against the primary server.
  • primaryPreferred: If the primary server is not available, SELECT queries are executed to a secondary server.
  • secondary: All SELECT queries are executed to the secondary servers.
  • secondaryPreferred: SELECT queries are executed to a secondary server if one is available. Otherwise, the queries are executed to the primary server.
  • nearest: SELECT queries are executed to the server with the least latency.

When to Use ReadPreference

When this property is set, query results may not reflect the latest changes if a write operation has not yet been replicated to a secondary machine. You can use ReadPreference to accomplish the following, with some risk that the driver will return stale data:

  • Configure failover queries: If the primary server is unavailable, you can set this property to "primaryPreferred" to continue to execute queries online.
  • Execute faster queries to geographically distributed replica sets: If your deployment uses multiple data centers, setting ReadPreference to "nearest" can result in faster queries, as the driver executes SELECT queries to whichever replica set member has the lowest latency.

When directing the driver to execute SELECT statements to a secondary server, SlaveOK must also be set. Otherwise, the driver will return an error response.

Copyright (c) 2023 CData Software, Inc. - All rights reserved.
Build 22.0.8462