Clean Up Old Data Automatically with MongoDB TTL Indexes

Clean Up Old Data Automatically with MongoDB TTL Indexes

With Big Data, comes well … a lot of data. But what if some of that data is only really useful within a certain timeframe?

Think about things like:

  • User sessions

  • Temporary tokens

  • Logs and audit trails

  • Time-sensitive cache

Luckily, MongoDB makes it easy to keep your collections tidy with what are called TTL indexes.

TTL (Time To Live) indexes automatically delete documents after a specified number of seconds and its as simple as adding a Datefield (and index on that field) to your documents.

Let’s say we add a Date field called created to each document, and then we add a TTL index like so:

---
db.sessions.createIndex(
  { "created": 1 },
  { expireAfterSeconds: 3600 }
);

MongoDB will then automatically remove (delete) any documents where created is older than 1 hour (which is 3600 seconds, if you don’t want to do the math). No manual cleanup jobs required!

Just make sure your date field is an actual Date object, not a string. You can find more about the Date type this helpful post: Quick Start: BSON Data Types – Date.