Automatic Data Expiration With expireAfterSeconds
Learners will configure the expireAfterSeconds option on a time series collection to automatically purge old measurements and control storage costs.
Automatic Data Expiration With expireAfterSeconds is a free MongoDB Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the MongoDB Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why Automatic Data Expiration Matters
Time series data is almost always finite in value — sensor readings from 5 years ago rarely inform today's decisions. Retaining stale data wastes storage, slows backups, and increases index sizes. MongoDB's expireAfterSeconds option lets you declare a retention period at collection creation time so the database handles cleanup automatically, without cron jobs or application-level delete routines.
Setting expireAfterSeconds at Creation
Pass expireAfterSeconds as a top-level option alongside the timeseries object when calling db.createCollection(). The value is an integer representing the number of seconds to retain data. Documents whose timeField value is older than now − expireAfterSeconds become eligible for deletion by the TTL background thread.
// Create a collection that retains data for 30 days
db.createCollection('sensorReadings', {
timeseries: {
timeField: 'timestamp',
metaField: 'sensorId',
granularity: 'seconds'
},
expireAfterSeconds: 60 * 60 * 24 * 30 // 2592000 seconds = 30 days
})How TTL Deletion Works for Time Series
MongoDB's TTL thread runs approximately every 60 seconds. For time series collections, it deletes entire bucket documents rather than individual measurements. A bucket is only deleted when all measurements it contains are older than the expiry threshold. This makes TTL deletion highly efficient — removing one bucket document deletes hundreds of measurements in a single operation.
Updating expireAfterSeconds on Existing Collections
You can modify the retention period of an existing time series collection at any time using the collMod command — no downtime required. Increasing the value keeps data longer; decreasing it causes previously non-expiring data to become eligible for deletion at the next TTL run. The change takes effect within roughly 60 seconds.
// Extend retention from 30 days to 90 days
db.runCommand({
collMod: 'sensorReadings',
expireAfterSeconds: 60 * 60 * 24 * 90 // 7776000 seconds
})
// Disable expiration entirely
db.runCommand({
collMod: 'sensorReadings',
expireAfterSeconds: 0
})TTL vs Regular Collection TTL Indexes
Regular MongoDB collections use a TTL index (a special single-field index on a date field with an expireAfterSeconds attribute) to expire individual documents. Time series collections use a different mechanism — they expire entire bucket documents rather than individual measurement documents. This means you cannot create a separate TTL index on a time series collection; expiration is managed solely through the collection-level expireAfterSeconds option.
// Regular collection TTL index (NOT for time series)
db.logs.createIndex(
{ createdAt: 1 },
{ expireAfterSeconds: 86400 } // deletes individual documents after 24h
)
// Time series uses collection-level option, not an index
// (The line below would fail on a time series collection)
// db.sensorReadings.createIndex({ timestamp: 1 }, { expireAfterSeconds: 86400 })Verifying the Expiration Setting
Inspect the current retention policy by running db.getCollectionInfos() and examining the options.expireAfterSeconds field. You can also check db.sensorReadings.stats() which reports the TTL configuration in its output. This is useful during audits to confirm production collections are set to the correct retention period.
// Check collection metadata including TTL
const info = db.getCollectionInfos({ name: 'sensorReadings' })
printjson(info[0].options)
// Output includes: { expireAfterSeconds: 2592000, timeseries: {...} }
// Check via stats
db.sensorReadings.stats()Tiered Retention With Multiple Collections
A common production pattern is tiered retention: raw high-frequency data is stored in one time series collection with a short TTL (e.g., 7 days), while an aggregation pipeline job runs nightly to compute hourly summaries and writes them to a second collection with a longer TTL (e.g., 2 years). This balances storage costs with the need to analyse historical trends.
// Raw readings — 7-day retention
db.createCollection('rawReadings', {
timeseries: { timeField: 'ts', metaField: 'deviceId', granularity: 'seconds' },
expireAfterSeconds: 60 * 60 * 24 * 7
})
// Hourly summaries — 2-year retention
db.createCollection('hourlyStats', {
timeseries: { timeField: 'hour', metaField: 'deviceId', granularity: 'hours' },
expireAfterSeconds: 60 * 60 * 24 * 730
})TTL Thread Timing and Accuracy
The TTL background thread wakes up every 60 seconds, so expiration is not instantaneous — data may survive up to 60 seconds beyond its threshold. On Atlas clusters under heavy load, TTL deletions may be further delayed. For compliance requirements demanding exact deletion at a specific second, manual deletion scripts or scheduled Atlas Triggers provide more deterministic control than TTL.
Manual Deletion for Immediate Cleanup
If you need to immediately remove a block of measurements — for example, to purge a faulty sensor's data — use deleteMany() with a filter on the timeField and metaField. Time series collections support deletes by time range and metaField value since MongoDB 5.1. Complex measurement-field filters on deletes are supported from MongoDB 6.0 onward.
// Delete all readings from a broken sensor before a cutoff date
db.sensorReadings.deleteMany({
sensorId: 'sensor-broken-99',
timestamp: { $lt: new Date('2024-06-01T00:00:00Z') }
})
// Delete readings older than a specific date for all sensors
db.sensorReadings.deleteMany({
timestamp: { $lt: new Date('2023-01-01T00:00:00Z') }
})Monitoring Expired Data Deletion
MongoDB exposes TTL deletion metrics in server status under the metrics.ttl section. The deletedDocuments counter tracks how many documents (bucket documents for time series) the TTL thread has deleted since the mongod process started. Monitoring this counter helps you confirm that TTL is actually running and deleting data as expected in production.
// Check TTL deletion metrics in mongosh
const status = db.serverStatus()
printjson(status.metrics.ttl)
// Output:
// {
// deletedDocuments: NumberLong(12345),
// passes: NumberLong(500)
// }Retention Planning Best Practices
When planning retention, consider three factors: compliance requirements (some regulations mandate data retention for years), analytical needs (how far back do your queries look?), and storage budget (what does keeping N days of data cost?). Model the storage growth by estimating daily document volume × average document size, then set expireAfterSeconds to balance all three constraints.
// Storage estimation helper
const docsPerDay = 60 * 60 * 24 // one reading per second = 86400
const avgDocBytes = 150 // approximate compressed document size
const retentionDays = 30
const totalBytes = docsPerDay * avgDocBytes * retentionDays
console.log('Estimated storage:', (totalBytes / 1e9).toFixed(2), 'GB')
// Outputs: Estimated storage: 0.37 GB for one sensor, 30 daysQuick Check
Test your understanding of MongoDB & NoSQL Databases concepts from this lesson.
Lesson Recap
In this lesson you learned: expireAfterSeconds is set at the collection level (not via an index) and controls when entire buckets are purged, collMod lets you update the retention period on a live collection without downtime, and tiered retention — short TTL for raw data, long TTL for pre-aggregated summaries — is the production best practice for cost-effective time series storage. Next up we cover authentication mechanisms in MongoDB.
Frequently asked questions
Is the “Automatic Data Expiration With expireAfterSeconds” lesson free?
Yes — the full text of “Automatic Data Expiration With expireAfterSeconds” is free to read here on the web, and the MongoDB Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the MongoDB Academy course, upgrade to CoddyKit PRO.
What will I learn in “Automatic Data Expiration With expireAfterSeconds”?
Learners will configure the expireAfterSeconds option on a time series collection to automatically purge old measurements and control storage costs. You practise MongoDB Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start MongoDB Academy?
No prior experience is required. MongoDB Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Automatic Data Expiration With expireAfterSeconds” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this MongoDB Academy lesson?
Yes. Every MongoDB Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Creating a Time Series Collection
- Inserting and Querying Time Series Data
- Windowed Aggregations on Time Series
- Automatic Data Expiration With expireAfterSeconds