MongoDB Academy · บทเรียน

การหมดอายุข้อมูลโดยอัตโนมัติด้วย expireAfterSeconds

ผู้เรียนจะกำหนดค่าตัวเลือก expireAfterSeconds ในคอลเลกชันอนุกรมเวลา เพื่อกำจัดการวัดค่าเก่าโดยอัตโนมัติและควบคุมต้นทุนการจัดเก็บข้อมูล

บทเรียน 4 จาก 413 ขั้นตอน

การหมดอายุข้อมูลโดยอัตโนมัติด้วย expireAfterSeconds เป็นบทเรียน MongoDB Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน 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 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.

เริ่มต้นได้ฟรี

เรียนรู้ JavaScript ด้วย AI tutor — ฟรี

เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป

คอร์ส
30
บทเรียน
120

คำถามที่พบบ่อย

บทเรียน “การหมดอายุข้อมูลโดยอัตโนมัติด้วย expireAfterSeconds” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การหมดอายุข้อมูลโดยอัตโนมัติด้วย expireAfterSeconds” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส MongoDB Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การหมดอายุข้อมูลโดยอัตโนมัติด้วย expireAfterSeconds”

ผู้เรียนจะกำหนดค่าตัวเลือก expireAfterSeconds ในคอลเลกชันอนุกรมเวลา เพื่อกำจัดการวัดค่าเก่าโดยอัตโนมัติและควบคุมต้นทุนการจัดเก็บข้อมูล คุณปฏิบัติ MongoDB Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน MongoDB Academy หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน MongoDB Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน

บทเรียน “การหมดอายุข้อมูลโดยอัตโนมัติด้วย expireAfterSeconds” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน MongoDB Academy นี้ได้ไหม

ได้ บทเรียน MongoDB Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การสร้างคอลเลกชันอนุกรมเวลา
  2. การแทรกและการค้นหาข้อมูลอนุกรมเวลา
  3. การรวมข้อมูลแบบหน้าต่างบนอนุกรมเวลา
  4. การหมดอายุข้อมูลโดยอัตโนมัติด้วย expireAfterSeconds
← กลับไปที่ MongoDB Academy