Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between readPreference and readConcern in MongoDB?

Tags:

mongodb

I read a lot the MongoDB documentation, but I couldn't understand the difference between readConcern and readPreference options.

For example: what is the result if I set 'majority' in my read concern option and 'primary' as a my read preference option? These two options seems contraditory.

I know that at query level I can only set the readConcern preference, but at client level I can set readPreference also.

like image 915
Krock Avatar asked Apr 27 '16 18:04

Krock


1 Answers

In a replica set the primary MongoDB instance is the master instance that receives all write operations.

The primary read preference is the default mode and concerns MongoDB clients; it's a driver/client option. That means you read data from the master instance where it is written first (before replicated to other replica set members).
If you use other modes than the primary read preference then you risk to read stale data.

Read concern is a query option for replica sets. By default the read concern is local. This returns the most recent data available at the time of the query execution. The data may not have been persisted to the majority of the replica set members and may be rolled back. The option can be set to majority, which will make the query read the most recent data that has been persisted to the majority of the replica set members and will not be rolled back. However you have to set that up properly (works only with WiredTiger engine and some other requirements...) and you might miss more recent data that is written but not persisted to the majority of replica set members.

Let's assume that you use default options for read preference and read concern. Then your MongoDB driver will route read request to the primary replica set member (master instance) and that instance would return the most recent data available at that moment. That data might not have been persisted to the majority of the replica set members and might be rolled back.

Similarly you can think of use cases where you use a different combination of the read concern and read preference options.

  • local / primaryPreferred
  • local / secondary
  • local / secondaryPreferred
  • local / nearest
  • majority / primaryPreferred
  • majority / secondary
  • majority / secondaryPreferred
  • majority / nearest

The options are described in the MongoDB Doc. Some combinations might make sense in some situations and some other combinations may make sense in other situations. I simply listed them here for completeness. And I'd interpret that as follows:

  1. the request is routed according to the read preference option (driver option)
  2. second the request is executed according to the read concern option (query option)
like image 124
Ely Avatar answered Nov 12 '22 10:11

Ely