TTL indexes
With a TTL index, documents delete themselves once their lifetime passes.
Make documents delete themselves once their lifetime passes, with a TTL index on a date field.
Requirements
- A user with
dbAdminorreadWriteon the database. - A date field in the documents.
Create the index
JavaScript
db.sessions.createIndex({ lastSeen: 1 }, { expireAfterSeconds: 3600 });Change the lifetime
JavaScript
db.runCommand({ collMod: "sessions", index: { keyPattern: { lastSeen: 1 }, expireAfterSeconds: 7200 } });Check
A session whose lastSeen is more than an hour old stops showing up in queries soon after.
Common problems
- A document without a date in that field, or with another type, never expires.