MongoDB TTL 인덱스 (자동 문서 삭제)1

// 데이터 삽입
db.collection.insertOne({
  name: 'Temporary',
  expireAt: new Date('2024-11-30T00:00:00Z'),
})

// TTL 인덱스 생성 (expireAt 시간 기준 삭제)
db.collection.createIndex({ expireAt: 1 }, { expireAfterSeconds: 0 })
  • 60초 간격 백그라운드 체크로 삭제 (즉시 아님)2
  • expireAt은 Date 값이어야 함 — 아니면 만료되지 않음3
  • 활용: 세션 만료, 캐시 관리, 임시 데이터

SQLite는 TTL 미지원 → 트리거 또는 외부 스케줄러로 구현


Footnotes

  1. Expire Data from Collections by Setting TTL | MongoDB: “To expire documents at a specific clock time, create a TTL index on a field that holds values of BSON date type or an array of BSON date-typed objects, and specify an expireAfterSeconds value of 0.” ↩

  2. TTL Indexes | MongoDB: “The background task that removes expired documents runs every 60 seconds.” ↩

  3. TTL Indexes | MongoDB: “If the indexed field in a document doesn’t contain one or more date values, the document will not expire.” ↩

#334