Try Studio 3T for Free
  1. Knowledge Base
  2. Query & CRUD Operations
  3. How to Query MongoDB Secondary Replica Set Members

How to Query MongoDB Secondary Replica Set Members

A common gotcha when first starting with MongoDB is that trying to query secondary replica set members (secondaries) does not seem to work.

For example, when issuing a simple query the user may be surprised to see errors such as:

Error: error: { "$err" : "not master and slaveOk=false", "code" : 13435 }

The gotcha here is that if you are connected to a MongoDB replica set and want to run the mongo shell (or alternatively the IntelliShell of Studio 3T, which offers the richest editing experience of any MongoDB client currently available) on a secondary member (for example, the replica set connection uses a read preference of secondary or secondaryPreferred), you will first need to run rs.slaveOk() to be able to query freely. This is because, by default, MongoDB does not permit read operations from non-master (that is, slave or secondary) instances.

In MongoDB, reads to a primary have strict consistency, meaning that the data it provides reflects the latest writes at all times. This is more familiar and easier to work with when coming from other database systems.

Reads to secondaries in MongoDB however, have eventual consistency, meaning that changes to the system can propagate gradually and readable members are not required to reflect the latest writes at all times. This is less common and may surprise some users coming from other database systems.

By calling rs.slaveOk() you are indicating to the system that you acknowledge that reads will be eventually consistent and wish to be able to query the secondary anyway. Following the principle of self-documenting code, rs.slaveOk() should really be called rs.iUnderstandThatHereReadsAreEventuallyConsistent AndIAmHappyToLiveWithTheConsequences SoPleaseLetMeQueryFreely(), but unless you have the amazing IntelliShell code completion available to you, that would be a little straining on the fingers.

OK, that’s it for this post. I hope you’re now a little more confident in querying MongoDB secondaries. If you enjoyed reading this tutorial, I’m sure you’ll also find our articles on MongoDB corner cases and querying workarounds and how to handle UUID data quite useful.

Updated on October 6, 2020

Was this article helpful?

Related Articles