How read preference modes really work?

I have a replica set: 1 primary & 2 secondaries. I want to set read preference mode to check read operations.

In my use case, I open 3 nodes in 3 mongosh terminal. I used to think read preference mode is synced between nodes, but I have to set it separately. In addition, even I set ‘secondary’ mode, primary node still can read data. Therefore, I wonder how read preference modes really work? And in production, what is the way client application can direct to read from specific nodes instead of using mongosh terminals?

Thank you!

Hi @npk72 ,

The read preference is a client option that instructs or guides the client which member or members of a repllicaset to read from. It can be set at the client level on the connectionString or client options. It can also be updated by the application for a specific database, collection or transaction.

Specific members can be targeted for secondary read by using replicaset tags. On MongoDB Atlas predefined tags can be used in the same manner.

To read from just one specific member connect directly by having it as the only host on the connection string and specify the connection option directConnection as true.

The following links provide much more detail.
https://www.mongodb.com/docs/manual/core/read-preference/#read-preference
https://www.mongodb.com/docs/manual/tutorial/configure-replica-set-tag-sets/#configure-replica-set-tag-sets
https://www.mongodb.com/docs/atlas/reference/replica-set-tags/#query-using-pre-defined-replica-set-tags

3 Likes

Hi @chris,

I have a replica set with 3 nodes: prim, sec1, sec2.
I want to check readPreference=primary to confirm that when the connectionString only has sec1, sec2, my query “find” can’t be perform (read only for primary). But when I’m running “find”, secondary still can return result. I’m using MongoDB Compass.

Could you please let me know my thinking is right or not? If right, how to config it to block read ops from secondary. And how to check read performance in replica set? Thank you

Unless Direct Connection is select Compass will connect to the primary regardless of which member(s) are on the connection sting or the readPreference. The connection string is a seed list, the topology of the cluster is discovered when the first member is connected to.

A better way to confirm that the secondary read preference is being used may be to run mongotop with the --json option and watch the count metric for a test collection.

If the cluster is very quiet and/or a larger amount of queries are executed using readPreference=secondary in a short period metrics of OpCounters would reflect the query load on the secondary.

1 Like