Rolling index build on a replica set (member by member)
MongoDBMaintenanceCommand
// 1) Shut down a SECONDARY; comment out replication.replSetName and start it standalone on another port:
// mongod --config /etc/mongod.conf --port 27217 --setParameter disableLogicalSessionCacheRefresh=true
// 2) Build the index on the standalone member:
db.getSiblingDB("shop").musteri.createIndex({ email: 1 }, { name: "idx_email" })
// 3) Restart with the normal configuration; wait until it is SECONDARY and lag has closed:
rs.printSecondaryReplicationInfo()
// 4) When all secondaries are done, step down the primary and apply steps 1-3 to the old primary:
rs.stepDown(120, 30)What it does
Builds the index on each member separately by temporarily running the member standalone outside the set; the primary never carries the build load.
When to use it
When the impact of the default distributed build on the primary and on replication lag is unacceptable for a very large collection.
Caution
Each member's maintenance time must be shorter than the oplog window; otherwise the member is too stale when it returns. When building a unique index the rolling way, stop writes to the collection for the whole build; otherwise some members may end up with violating documents. Start the standalone member on a different port so applications do not connect to it.