创建 TTL 索引、更改其过期时间并监控 TTL 删除
MongoDB维护命令
// Automatically delete documents lastSeen + 3600 s later:
db.oturum.createIndex({ lastSeen: 1 }, { expireAfterSeconds: 3600, name: "ttl_lastSeen" })
// Change the expiry without rebuilding the index:
db.runCommand({ collMod: "oturum", index: { name: "ttl_lastSeen", expireAfterSeconds: 7200 } })
// TTL indexes on the collection and their expiry:
db.oturum.getIndexes().filter(i => i.expireAfterSeconds !== undefined)
// TTL monitor statistics (deleted documents, passes):
db.serverStatus().metrics.ttl作用
创建 TTL 索引,在日期字段之后的设定时间自动删除文档;用 collMod 更改过期时间而无需重建;并显示 TTL monitor 已删除的文档数。
适用场景
用于清理会话、日志或临时令牌等有时效的数据,而无需在应用中编写删除作业,以及排查不断增长的集合为何没有缩小。
注意
TTL monitor 默认每 60 秒运行一次;删除不是即时的。该字段必须是 Date 类型(或 Date 数组);字符串日期或缺少该字段的文档永远不会被删除。缩短过期时间会导致大量文档被一次性删除,产生写入负载和复制延迟。删除只在 primary 上发生,并写入 oplog。