This is not a basic question on just asking about mongo cluster. It is not a duplicate in my opinion I have a mongodb 3 node cluster and my url is something along the following lines in a PlayFramework conf file
mongodb.uri = "mongodb://mongodb1:27017,mongodb2:27017,mongodb3:27017/myproj"
By default when the replica is configured, all reads and writes are happening only on Primary and that is what I want. I however, want the reads to go to secondary when no primary is left, that is when 2 nodes go down, there will not be a primary left and only one secondary.
I do not want to modify my code to achieve this for each read query. I tried the following on the secondary node but it does not help
db.getMongo().setReadPref('primaryPreferred')
What exactly do I need to do to make this work?
I do not want to modify my code to achieve this for each read query. I tried the following on the secondary node but it does not help:
db.getMongo().setReadPref('primaryPreferred')
You are on the right track with read preferences, but need to set this in your connection string or driver. Setting a read preference in the mongo shell only affects the current shell session, and has no effect on remote connections.
mongodb.uri = "mongodb://mongodb1:27017,mongodb2:27017,mongodb3:27017/myproj"
You need to add some additional parameters as per MongoDB's Connecting String URI Format:
replicaSet=... option indicates that the driver should use "replica set" connection mode as opposed to the default direct connection mode. This parameter enables replica set monitoring, read preferences, and discovery of topology changes. The provided replica set name must match the replica set name configured for your deployment. For full details on the connection behaviour expected for officially supported MongoDB Drivers, see the Server Discovery and Monitoring (SDAM) specification. The rationale section of the spec includes answers to common questions about the chosen approach.readPreference=primaryPreferred option indicates the preference to read from a primary but use a secondary if there is no primary available.maxStalenessSeconds=... option which limits the maximum replication lag (or staleness) when using a secondary read preference. By default there is no max staleness so the driver will not consider replication lag when selecting a secondary based on read preference. If your intent is to use primaryPreferred as a failover option for reads I would set max staleness with caution: you need to ensure that you have at least one secondary which has acceptable staleness. So, assuming a replica set name of mongocluster and database of myproj the suggested connection string would be:
mongodb://mongodb1:27017,mongodb2:27017,mongodb3:27017/myproj?replicaSet=mongocluster&readPreference=primaryPreferred
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With