Expiring and automatically deleting documents after a period of time using a TTL (time to live) index in MongoDB

Expiring and automatically deleting documents after a period of time using a TTL (time to live) index in MongoDB

TTL or Time To Live represent the expiration time or the period for a given documents to stay in our collection before it gets deleted and removed automatically from our collection. It can be used for a lot of cases like a session, some temporary data, logs, etc... The TTL feature relies on a background thread in mongod that reads the date-typed values in the index and removes expired documents from the collection.

To define a ttl index we use the createIndex with some additional parameter which is expireAfterSeconds that specifies a value, in seconds, as a TTL to control how long MongoDB retains documents in this collection.

The ttl index can only works on dates fields

Creating a TTL index

To create a ttl index we'll use the createIndex with the option expireAfterSeconds set to 60 second.

db.articles.createIndex({createdAt: 1}, {expireAfterSeconds: 60})

Inserting data for testing

db.articles.insert({createdAt: new Date()})

MongoDB will automatically delete documents from the articles collection when the document’s createdAt value is older than the number of seconds specified in expireAfterSeconds.

Querying our collection

If we query our collection after 1 minute we'll see that our collection is empty and have no documents. Every documents get deleted after 1 minute as specified by expireAfterSeconds.

db.articles.find()