---
title: MongoDB TTL 索引与过期数据清理实践
keywords: TTL index, expireAfterSeconds, Date, background, cleanup
description: 使用 TTL 索引对基于时间的文档自动过期清理,示例包含索引创建、插入与行为说明。
tags:
- Date
- MongoDB
- TTL index
- background
- cleanup
- expireAfterSeconds
- 数据库
- 维护
categories:
- 文章资讯
- 技术教程
---
创建 TTL 索引(按字段过期时间):
db.sessions.createIndex({ expiresAt: 1 }, { expireAfterSeconds: 0 })
插入示例(1 小时后过期):
db.sessions.insertOne({ userId: 1, expiresAt: new Date(Date.now() + 3600*1000) })
查看索引与说明:
db.sessions.getIndexes()
# TTL 删除由后台任务执行,非实时,通常在分钟级触发;仅支持单字段索引。

发表评论 取消回复