Measure the oplog window and replication lag
MongoDBReplica SetCommand
// Oplog size and the time span it covers (oplog window):
rs.printReplicationInfo()
// Lag of each secondary relative to the primary:
rs.printSecondaryReplicationInfo()
// Lag in seconds and sync source, for monitoring/scripts:
const s = rs.status(); const p = s.members.find(m => m.stateStr === "PRIMARY");
s.members.filter(m => m.stateStr === "SECONDARY").map(m => ({ host: m.name, lagSec: (p.optimeDate - m.optimeDate) / 1000, syncSource: m.syncSourceHost }))
// Window (hours):
db.getReplicationInfo().timeDiffHoursWhat it does
Shows how many hours of writes the oplog holds (oplog window) and how many seconds each secondary is behind the primary, together with its sync source.
When to use it
On a replication lag alert, before planned maintenance to calculate how long a member can stay down, and after bulk write jobs.
Caution
If a member stays down longer than the oplog window it becomes 'too stale' and needs an initial sync. Bulk update/delete jobs can shrink the window within hours; judge the window by its value at peak load. The lag calculation is based on the optimeDate difference; if the primary receives no writes, lag does not look high but the window does not shrink either.