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 Date field (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.

,

MongoDB for Jobseekers Book

If you’re fascinated by the intricacies of MongoDB and yearn to explore its limitless possibilities further, I invite you to delve into my comprehensive book, “MongoDB for Jobseekers.”

This book is your passport to unlocking MongoDB’s full potential, whether you’re a beginner or an experienced enthusiast. Seamlessly navigate the intricacies of data management, uncover advanced techniques, and gain insights that will elevate your proficiency.

Available on Amazon and other leading platforms, “MongoDB for Jobseekers” offers a comprehensive roadmap for honing your MongoDB skills. As you embark on your journey through the world of databases, this book will be your trusted companion, guiding you towards mastery and helping you stand out in the competitive landscape.