使用 expireAfterSeconds 自动过期数据
学习者将为时间序列集合配置 expireAfterSeconds 选项,自动清除旧测量数据并控制存储成本。
使用 expireAfterSeconds 自动过期数据 是 CoddyKit 上的免费 MongoDB Academy 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 MongoDB Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 MongoDB Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
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.
常见问题解答
「使用 expireAfterSeconds 自动过期数据」课时是免费的吗?
是的 — 「使用 expireAfterSeconds 自动过期数据」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 MongoDB Academy 课程的其余内容,请升级到 CoddyKit PRO。 MongoDB Academy 课程共包含 4 节课。
「使用 expireAfterSeconds 自动过期数据」这节课中我会学到什么?
学习者将为时间序列集合配置 expireAfterSeconds 选项,自动清除旧测量数据并控制存储成本。 你通过在浏览器中直接运行的动手代码来练习 MongoDB Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 MongoDB Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 MongoDB Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「使用 expireAfterSeconds 自动过期数据」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 MongoDB Academy 课中编写并运行代码吗?
能。每节 MongoDB Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 创建时间序列集合
- 插入和查询时间序列数据
- 对时间序列执行窗口聚合
- 使用 expireAfterSeconds 自动过期数据