# MongoDB Read Preference: When to Read From Secondaries

> MongoDB read preference explained: primary, secondary, nearest, maxStalenessSeconds, tag sets and Atlas analytics nodes, plus when reading from secondaries is safe.

Source: https://bussolaformongo.app/blog/mongodb-read-preference-guide/ · 2026-11-19

A MongoDB read preference tells the driver which members of a replica set may serve a read. The default, `primary`, sends every read to the primary and returns the latest acknowledged data. The other four modes (`primaryPreferred`, `secondary`, `secondaryPreferred`, `nearest`) allow reads from secondaries, which can offload the primary or reduce latency, at the price that those reads may be slightly behind. Use a non-primary read preference only for queries that tolerate stale data, such as reporting, dashboards or analytics, and keep everything that must read its own writes on the primary.

## What read preference controls (and what it doesn't)

Read preference is a client-side setting. The driver monitors the replica set, keeps a list of members with their roles and round-trip times, and picks one that matches your mode for each operation. It is not a server permission: any client can ask for any mode.

It also does not change what data a member holds. Secondaries apply the primary's oplog asynchronously, so a secondary is always some amount of replication lag behind. Under normal conditions that lag is small, but it can grow during heavy write bursts, slow disks, network trouble or an initial sync.

Two related settings are easy to confuse with it:

- **Read concern** (`local`, `majority`, `snapshot`, ...) controls what consistency guarantee the returned data has.
- **Write concern** controls when a write is acknowledged.

A read from a secondary with `readConcern: "majority"` returns data that is majority-committed as seen by that secondary, but it can still be older than what the primary has.

## The five modes

| Mode | Behavior |
| --- | --- |
| `primary` | Only the primary. Errors if there is no primary. This is the default. |
| `primaryPreferred` | The primary if available, otherwise a secondary. |
| `secondary` | Only secondaries. Errors if none is available. |
| `secondaryPreferred` | A secondary if available, otherwise the primary. |
| `nearest` | Any eligible member (primary or secondary) with low network latency. |

### primary and primaryPreferred

`primary` is the only mode that lets you see your own acknowledged writes reliably. Multi-document transactions must use it: you cannot run a transaction with any other read preference.

`primaryPreferred` is a reasonable choice for read-heavy services that want to stay available during an election. While there is no primary, reads fall back to a secondary instead of failing. Be aware that during that window the application silently starts reading possibly stale data.

### secondary and secondaryPreferred

`secondary` never reads from the primary, even if no secondary is reachable, in which case the operation fails with a server selection error. `secondaryPreferred` is usually the friendlier option: it uses secondaries in normal operation and falls back to the primary if none is available, for example in a single-node development replica set.

If several secondaries qualify, the driver spreads reads among those within the latency window rather than always choosing the single fastest one.

### nearest

`nearest` ignores the primary/secondary distinction and chooses among all eligible members by latency. A member is eligible if its round-trip time is within a window of the fastest one; the window defaults to 15 ms and is configurable with `localThresholdMS`. It suits geographically distributed deployments where reading from a member in your region matters more than freshness.

## Setting it in a connection string

The mode can be part of the URI, so every operation on that client inherits it:

```text
mongodb+srv://appuser:<password>@cluster0.example.mongodb.net/shop?readPreference=secondaryPreferred&maxStalenessSeconds=120
```

In mongosh you can set it for the session or for a single cursor:

```js
// For the current shell session
db.getMongo().setReadPref("secondaryPreferred")

// For a single cursor
db.orders.find({ status: "shipped" }).readPref("secondary")
```

Drivers also let you set it per database, collection or operation. In Node.js, for example:

```js
const { ReadPreference } = require("mongodb");

const orders = client
  .db("shop")
  .collection("orders", { readPreference: ReadPreference.SECONDARY_PREFERRED });

const report = await orders
  .aggregate([{ $group: { _id: "$status", n: { $sum: 1 } } }])
  .toArray();
```

The more specific scope wins: an operation-level setting overrides the collection, which overrides the database, which overrides the client.

## Limiting staleness with maxStalenessSeconds

With any mode other than `primary`, you can tell the driver to skip secondaries that are too far behind using `maxStalenessSeconds`. The driver estimates each secondary's staleness from heartbeat information and excludes members above your limit.

Things to know:

- The smallest value allowed is 90 seconds. Smaller numbers are rejected, because the estimate depends on heartbeat and idle-write intervals and cannot be more precise than that.
- If no secondary meets the limit, the read falls back according to the mode: `secondaryPreferred` goes to the primary, while `secondary` fails.
- It does not apply to `primary`.

It is a safety net, not a consistency guarantee. A secondary that is 80 seconds behind still passes a 90-second limit.

## Tag sets and Atlas analytics nodes

Replica set members can carry tags, arbitrary key/value labels defined in the replica set configuration. A tag set list lets you route reads to specific members, such as those in one data center. Tag sets are tried in order, and an empty document `{}` at the end means "any eligible member":

```js
db.orders.find({ status: "shipped" }).readPref("secondary", [
  { region: "eu", workload: "reporting" },
  { region: "eu" },
  {}
])
```

In a connection string, repeat the `readPreferenceTags` option, one per tag set:

```text
?readPreference=secondary&readPreferenceTags=region:eu,workload:reporting&readPreferenceTags=
```

The trailing empty `readPreferenceTags=` is the fallback to any member.

On MongoDB Atlas, tags are how you reach dedicated analytics nodes. Analytics nodes are extra read-only members that do not participate in elections and are meant for long-running queries so they do not compete with operational traffic. Atlas labels them with the tag `nodeType:ANALYTICS`, and the connection options shown for your cluster give the exact form. A typical analytics connection looks like this:

```text
mongodb+srv://reporter:<password>@cluster0.example.mongodb.net/shop?readPreference=secondary&readPreferenceTags=nodeType:ANALYTICS
```

Whether your cluster has analytics nodes depends on how it is configured and on its tier, so check the cluster settings first. Pair this with a database user that only has the `read` role, so reporting tools cannot write anywhere.

## When secondary reads are a good idea

Good fits:

- Dashboards and reports that tolerate seconds or minutes of delay.
- Long aggregations that would otherwise compete with application queries. The [aggregation cheat sheet](/blog/mongodb-aggregation-cheat-sheet/) covers pipelines that typically fall into this category.
- Read scaling for catalog-style data that changes rarely.
- Latency-sensitive reads in remote regions, using `nearest`.

Poor fits:

- Read-after-write flows: a user saves a profile and the next page loads from a secondary that has not replicated it yet.
- Anything inside a transaction.
- Decisions that act on the data, such as checking stock before accepting an order.
- Queries that need a consistent view across several reads, unless you use causally consistent sessions or the primary.

If you need read-your-writes on secondaries, causally consistent sessions combined with majority read and write concerns can provide it, at some cost in latency. For most applications, reading those paths from the primary is simpler.

## Sharded clusters

In a sharded cluster the driver passes the read preference to `mongos`, which applies it per shard when it routes the query. A `secondary` preference therefore reads from a secondary of each involved shard. Replication lag is per shard, so results that combine shards can reflect slightly different points in time. Avoid relying on exact counts from secondary reads in a cluster that is rebalancing. See [countDocuments vs estimatedDocumentCount](/blog/countdocuments-vs-estimateddocumentcount/) for why counts are already subtle on sharded data.

## Common mistakes

1. **Using `secondary` as a global default.** A single-member or degraded replica set then fails every read. Prefer `secondaryPreferred` unless failing is the intent.
2. **Reading from secondaries to "fix" a slow query.** A missing index is slow on every member. Look at the plan first, as described in [reading explain output](/blog/mongodb-explain-collscan-ixscan/).
3. **Expecting exact counts.** Counts and listings from a lagging secondary can differ from the primary for a while.
4. **Forgetting that writes ignore it.** Writes always go to the primary regardless of read preference.
5. **Ignoring lag when debugging.** If two tools return different results for the same query, compare their read preferences before suspecting corruption. In mongosh, `rs.printSecondaryReplicationInfo()` shows how far each secondary is behind.

When you check data from a phone during an incident, the same caution applies: know which member your client is reading from before trusting a number that looks wrong. The [on-call checklist](/blog/mongodb-on-call-checklist/) lists other quick checks worth doing first.

## Checklist

- Default to `primary`; opt in per workload, not globally.
- Prefer `secondaryPreferred` over `secondary` for resilience.
- Set `maxStalenessSeconds` (90 or more) for secondary reads where freshness matters.
- Use tag sets or the Atlas `nodeType:ANALYTICS` tag to isolate heavy queries.
- Never use a non-primary mode for transactions or read-after-write paths.
- When two clients disagree, compare their read preferences and replication lag first.
