Create a TTL index, change its expiry and monitor TTL deletes
MongoDBMaintenanceCommand
// Automatically delete documents lastSeen + 3600 s later:
db.oturum.createIndex({ lastSeen: 1 }, { expireAfterSeconds: 3600, name: "ttl_lastSeen" })
// Change the expiry without rebuilding the index:
db.runCommand({ collMod: "oturum", index: { name: "ttl_lastSeen", expireAfterSeconds: 7200 } })
// TTL indexes on the collection and their expiry:
db.oturum.getIndexes().filter(i => i.expireAfterSeconds !== undefined)
// TTL monitor statistics (deleted documents, passes):
db.serverStatus().metrics.ttlWhat it does
Creates a TTL index that automatically deletes documents a set time after a date field, changes the expiry with collMod without a rebuild, and shows how many documents the TTL monitor has deleted.
When to use it
To clean up time-bound data such as sessions, logs or temporary tokens without writing a delete job in the application, and to investigate why a growing collection is not shrinking.
Caution
The TTL monitor runs every 60 seconds by default; deletion is not instant. The field must be of type Date (or an array of Dates); string dates or documents without the field are never deleted. Shortening the expiry causes many documents to be deleted at once, write load and replication lag. Deletes happen only on the primary and are written to the oplog.