KeplerGrid guide

Expire MongoDB documents with a TTL index

Create a TTL index using a BSON date field and check the expiration rule. Learn which documents remain and why deletion can lag.

Load the practice collection

Run once in mongosh against a development instance with an empty practiceSessions practice collection.

const lab = db.getSiblingDB("keplergrid_practice")
lab.practiceSessions.insertMany([
  { _id: "expires-later", expiresAt: new Date(Date.now() + 3600000) },
  { _id: "no-expiry" },
  { _id: "legacy-string", expiresAt: "2020-01-01T00:00:00.000Z" }
])

In KeplerGrid, open keplergrid_practice.practiceSessions with a Read only connection.

Create the index on a disposable collection

Run this only on the disposable practice database. The background TTL process deletes eligible documents automatically. With an interval of zero, each BSON date is the document’s deadline. A positive interval adds that many seconds to the date.

lab.practiceSessions.createIndex(
  { expiresAt: 1 },
  { name: "expire_practice_sessions", expireAfterSeconds: 0 }
)

Open the collection’s Indexes tab in KeplerGrid and look for expire_practice_sessions with key expiresAt.

Read the exact expiration setting

Use getIndexes() in the same shell session to inspect the configured interval.

lab.practiceSessions.getIndexes().find(
  index => index.name === "expire_practice_sessions"
)

TTL indexes use one field. The sample’s missing date and legacy string are ineligible. Deletion runs in the background, so a document can remain visible after its deadline. Check how many records are already eligible before creating or shortening a TTL rule on existing data.

See how to query dates with explicit boundaries or revisit the related KeplerGrid walkthrough.