MongoDB: Global read preference (set via connection string) vs Query level read preference (set as options in query), which takes precedence?

Viewed 36

I am running a mongoDB cluster. A nodejs application connects to this db and I have set readPreference= secondaryPreferred. However there is one critical flow which writes the document and then subsequently reads the same document. While we read it, we are getting stale reads,to avoid this, we wanted to set read preference to primary in that specific query which is fetching the same document. Since the global read preference(via connection string) is set to secondary and one of the query is setting read preference via query, does mongoDb prioritise between two? or will global preference override query specific preference? I couldn't get this in below mongodb docs.

https://www.mongodb.com/docs/manual/core/read-preference/

1 Answers

We were able to provide the read preference as an option to find function of mongoose.

await UserModel.findOne(query, {}, {readPreference : 'primary'});

The global read preference was set to secondary in connection string as below:

mongodb://db0.example.com,db1.example.com,db2.example.com/?replicaSet=myRepl&readPreference=secondary

The query did honor the parameter sent over query options and was reading data from primary

Related