MongoDB officially does not allow adding secondary only indexes in a replica set. However, there is one hacky way to achieve the same.
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.
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.
- Add a new member to the replica set (or pick an existing one)
- Make this member a non-voting member. This step is essential because we never want this member to become a primary, ever.
- Remove the member from the replica set - instructions
- Add the indexes you need
- Add the member back to the replica set
- 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.