MongoDB provides a built-in mechanism to automatically delete documents after a certain period using TTL (Time-To-Live) indexes.
If your documents contain an expiration timestamp (e.g., expiresAt), you can create a TTL index to automatically remove expired records:
db.password_reset.createIndex({ expiresAt: 1 }, { expireAfterSeconds: 0 })- The
expiresAtfield must be of typeDate. - The index ensures that documents are deleted as soon as their
expiresAttimestamp is reached. expireAfterSeconds: 0means the document is removed exactly at the givenexpiresAttime.
To check if the TTL index was successfully created, run:
db.password_reset.getIndexes()This should display an entry with expireAfterSeconds: 0.
Verify that your documents store expiresAt as an ISODate:
db.password_reset.find({}, { expiresAt: 1 }).limit(5)If necessary, convert it:
db.password_reset.updateMany(
{},
[{ $set: { expiresAt: { $toDate: "$expiresAt" } } }]
)TTL indexes provide an efficient way to automatically remove expired documents without requiring manual cleanup or cron jobs.