0Pricing
MongoDB Academy · Lektion

Automatisches Ablaufen von Daten mit expireAfterSeconds

Lernende konfigurieren die Option expireAfterSeconds für eine Zeitreihensammlung, um alte Messwerte automatisch zu löschen und Speicherkosten zu kontrollieren.

Automatisches Ablaufen von Daten mit expireAfterSeconds ist eine kostenlose MongoDB Academy-Lektion auf CoddyKit. Dies ist Lektion 4 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des MongoDB Academy-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der MongoDB Academy-Kurs umfasst insgesamt 4 Lektionen.

Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.

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 days

Quick 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.

Häufig gestellte Fragen

Ist die Lektion „Automatisches Ablaufen von Daten mit expireAfterSeconds“ kostenlos?

Ja — der vollständige Text von „Automatisches Ablaufen von Daten mit expireAfterSeconds“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des MongoDB Academy-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der MongoDB Academy-Kurs umfasst insgesamt 4 Lektionen.

Was lerne ich in „Automatisches Ablaufen von Daten mit expireAfterSeconds“?

Lernende konfigurieren die Option expireAfterSeconds für eine Zeitreihensammlung, um alte Messwerte automatisch zu löschen und Speicherkosten zu kontrollieren. Du übst MongoDB Academy mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.

Brauche ich Erfahrung, um MongoDB Academy zu starten?

Keine Vorkenntnisse erforderlich. MongoDB Academy auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 4 von 4.

Wie lange dauert die Lektion „Automatisches Ablaufen von Daten mit expireAfterSeconds“?

Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.

Kann ich in dieser MongoDB Academy-Lektion Code schreiben und ausführen?

Ja. Jede MongoDB Academy-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.

Alle Lektionen in diesem Kurs

  1. Eine Time-Series-Collection erstellen
  2. Zeitreihendaten einfügen und abfragen
  3. Fensterbasierte Aggregationen für Zeitreihen
  4. Automatisches Ablaufen von Daten mit expireAfterSeconds
← Zurück zu MongoDB Academy