About Now

MongoDB secondary only index

MongoDB officially does not allow adding secondary only indexes in a replica set. However, there is one hacky way to achieve the same.

Why

Sometimes you might have requirements which may not be needed for the main application. An actual use case is when you want to run analytics (or use things like Metabase) but don’t want to change the primary schema.

How

Earlier, I discovered an odd behaviour with MongoDB replica set and indexes. I thought one could use a similar approach to add secondary only indexes, which is what people have been doing.

The procedure is almost similar to how MongoDB adds rolling indexes to replicas but slightly different.

  1. Add a new member to the replica set (or pick an existing one)
  2. Make this member a non-voting member. This step is essential because we never want this member to become a primary, ever.
  3. Remove the member from the replica set - instructions
  4. Add the indexes you need
  5. Add the member back to the replica set
  6. Now connect to only this instance for analytics or other purposes

You might need to repeat steps 3-5 if you want to add new indexes.

References

  1. Bunch of Jira tickets - 1, 2
  2. Stackoverflow - 1, 2
  3. My previous blog post where I discovered that you can add duplicate records on an unique index