It is often necessary to delete data after a time or automatically expire it after a certain age. For example, this could happen during a user password reset when you send a temporary link via email. I recently discovered a useful MongoDB feature called Time To Live (TTL) indexes, which automatically deletes data. Here is how to set it up.
Prerequisites
- A MongoDB instance somewhere, you could create one in DigitalOcean to try this
- An understanding of how to get shell access to your MongoDB server, you can do this with mongosh
- Optional: A MongoDB GUI, I use MongoDB Compass it has everything you need (including a shell)
Step 1 - Create a Database
Our first step is to create a database, to do that we can open our mongo shell and run this command:
Step 2 - Create the TTL Index
Next, we need to do the most important part for data to automatically expire, we will create a TTL index on the field we want in a collection that will contain records. We’ll create the index on the “createdAt” field and set “expireAfterSeconds” is set to a time limit. I’ve chosen 1 hour for this purpose:
Step 3 - Insert a Record
And that's actually all we need to do to, now if we insert a record that matches the index above, it will automatically be removed! For example, suppose we are using this collection to store session data that lasts an hour:
If you check back in an hour, the record will be gone.
Conclusion
And that's how you can automatically expire records in a MongoDB collection, it's simple and if you'd like to read more about the TTL index, here is a link to the MongoDB docs. Happy coding! 🧑💻