How to read from secondary node?

how to read from secondary node?
i try to connect to secondary using mongo shell, i should first use rs.secondaryOk(), then i can select data.
i know there is read preference config in client connectstring which can be setted to read from secondary, it there some parameter like rs.secondaryOk() in my connectstring?
or does dirver auto set secondaryOk when connect to secondary node?

Hi @Yi_deng and welcome to MongoDB community forums!!

By default, the read operation in a replica set if performed at the Primary node as the secondary members are involved in synching with the primary member in an asynchronous fashion.
The behaviour of read preference is described in the documentation for Read Preference in Replica Set.

If you wish to specify to read from the secondary, you can set the flag value to readPreference=secondary in the connection string.
You can also specify db.getMongo().setReadPref(‘secondary’) to allow read from the secondary member of the replica sets.

The rs.secondaryOk() was used in the older version till MongoDB 4.0, and now no longer supported. Therefore, the recommendation would be to use latest MongoDB version for supported commands and new features.

Please feel free to reach out in case of any further queries.

Best Regards
Aasawari

Is it possible to parse readpreferance to primarypreferred while even connecting to secondary node like what i need to add in commands
$ mongosh localhost -readPreferance primaryPreferred

could you correct it ?

Hi Aasawari / Team
Can you respond to my query above. TIA
Regards

Hi @Amit_Kumar41 and welcome to the community forum!!

If I understand correctly, you are trying to set the readPreference to primaryPreferred which you are trying to connect to the replica set member.
The documentation on How to Configure Read Preference describes how you can add the tag to the connection string.

Please do not hesitate to reach out if you are facing any issues while making the connection.

Best Regards
Aasawari

1 Like

Hi Aasawari,

Thanks , i shall check this and get back to you, meanwhile if you can get me a just direct string while connecting to db using mongosh and readpref as ‘secondary’ .

Regards

[quote=“Amit_Kumar41, post:7, topic:254656”]
Hi Aasawari,

Thanks , i shall check this and get back to you, meanwhile if you can get me a just direct string while connecting to db using mongosh and readpref as ‘secondary’ .

Regard