Automatically Age Out MongoDB® Collection Documents

2 min read
Automatically Age Out MongoDB® Collection Documents


One of the common scenarios in working with a database is to automatically prune some tables based on time. For example, you might have a jobs table to track background jobs in your product and you only want to keep jobs for the last hour. How it’s typically implemented is that you end up writing a daemon process that runs periodically and garbage-collects your tables. Given this is such a common process, the folks at MongoDB have built this functionality into the database which can be leveraged in your MongoDB deployments! It’s called “TTL indexes”. Here’s how you can use TTL indexes in two simple steps:

Step 1: Add a Date Field

Add a date field to your document to indicate the age of the document. MongoDB will use this field to determine if your document is expired and needs to be removed. If you wish to keep the document around longer, just update this document with an updated date. In the example below I have added a “creationTime” field to my jobs collection: {
   "name" : testjob
   "creationTime": new Date('Oct 30, 2013: 11:00:00'),
   "type": 2,
} )

Step 2: Add a TTL Index

Add a TTL index to your collection on this field. In this example below, we’ll use an expireAfterSeconds value of 3600. This will expire jobs after every hour: { "creationTime": 1 }, { expireAfterSeconds: 3600 } )

The TTL daemon run every 60 seconds, so your document will be deleted within approximately 60 seconds of expiry. Another advantage of TTL indexes is that they also behave like normal indexes – so you can query on the date field and the query plan will use the index. For more details, refer to the MongoDB documentation on TTL indexes.

For more information, please visit Connect with ScaleGrid on LinkedIn, X, Facebook, and YouTube.
Table of Contents

Stay Ahead with ScaleGrid Insights

Dive into the world of database management with our monthly newsletter. Get expert tips, in-depth articles, and the latest news, directly to your inbox.

Related Posts

distributed storage system

What is a Distributed Storage System

A distributed storage system is foundational in today’s data-driven landscape, ensuring data spread over multiple servers is reliable, accessible, and...

MySQL Backups: Methods & Best Practices

Regarding MySQL backups, knowing how to secure your data is crucial. This guide cuts through the complexity, providing instructions on...

Crucial Redis Monitoring Metrics You Must Watch

Redis® is an in-memory database that provides blazingly fast performance. This makes it a compelling alternative to disk-based databases when...


Add Headline Here