liveBook · Manning

TTL index

As explained in MongoDB 8.0 in Action, Third Edition

A TTL index is a MongoDB index that automatically expires and removes documents according to an indexed date field and expiration interval.

A TTL index automatically deletes documents after a duration or at a specified time. It suits short-lived data such as logs, sessions, machine-generated events, temporary files, and expired offers. section 1.3.1 section 7.4.3

Configure a TTL index by following these rules:

  • Create it with createIndex() on a single date field or an array containing date values. section 7.4.3
  • Set expireAfterSeconds to the retention period, from 0 through 2147483647. section 7.4.3
  • Use expireAfterSeconds: 0 when each document's BSON date specifies its exact expiration time. section 7.4.3
  • Change an existing TTL setting with collMod, and remember that hidden indexes still perform TTL deletions. section 7.4.3 section 7.8
db.getSiblingDB('sample_analytics').transactions.createIndex(
    { "date": 1 },
    { expireAfterSeconds: 31536000 } // Creates a TTL index on
➥the "date" field. Documents will expire 1 year after the
➥value in the "date" field.
)

Creates a one-year TTL index on the transactions collection's date field. section 7.4.3

How MongoDB 8.0 in Action, Third Edition covers it

How deep it goes
Defines single-field date indexing, duration-based expiration, scheduled expiration, and collMod updates without detailing the deletion mechanism.
Examples
Uses flight documents, sessions, temporary files, promotional offers, and one-year expiration for transactions.
What you can do after
Operate/configure automatic deletion with createIndex(), expireAfterSeconds, and collMod for duration-based or scheduled expiration.
How it connects
Connects TTL indexes with capped collections, partial indexes, time-series collections, hidden indexes, and index management.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of MongoDB 8.0 in Action, Third Edition. The section links point to the parts of the book it draws on.