为时间序列集合设置自动删除(TTL)
当你创建一个时间序列集合时,你可以通过使用expireAfterSeconds 参数设置自动删除超过指定秒数的旧文档
db.createCollection(     "weather24h",     {        timeseries: {           timeField: "timestamp",           metaField: "metadata",           granularity: "hours"        },        expireAfterSeconds: 86400     } ) 
过期阈值是 timeField 字段值加上指定的秒数。考虑以下 weather24h 集合中的文档
{    "metadata": {"sensorId": 5578, "type": "temperature"},    "timestamp": ISODate("2021-05-18T10:00:00.000Z"),    "temp": 12 } 
文档将在 "2021-05-19T10:00:00.000Z" 从数据库中过期。一旦一个桶中的所有文档都过期,删除过期桶的背景任务将在下一次运行时删除该桶。更多信息请参阅删除操作的定时。
在集合上启用自动删除
要为现有的时间序列集合启用文档的自动删除,请发出以下 collMod 命令
db.runCommand({    collMod: "weather24h",    expireAfterSeconds: 604801 }) 
更改 expireAfterSeconds 参数
要更改 expireAfterSeconds 参数值,请发出以下 collMod 命令
db.runCommand({    collMod: "weather24h",    expireAfterSeconds: 604801 }) 
检索 expireAfterSeconds 的当前值
要检索 expireAfterSeconds 的当前值,请使用 listCollections 命令
db.runCommand( { listCollections: 1 } ) 
结果文档包含一个时间序列集合的文档,其中包含 options.expireAfterSeconds 字段。
{     cursor: {        id: <number>,        ns: 'test.$cmd.listCollections',        firstBatch: [          {             name: <string>,             type: 'timeseries',             options: {                expireAfterSeconds: <number>,                timeseries: { ... }             },             ...          },          ...        ]     }  } 
禁用自动删除
要禁用自动删除,请使用 collMod 命令将 expireAfterSeconds 设置为 off
db.runCommand({     collMod: "weather24h",     expireAfterSeconds: "off" }) 
行为
删除操作的时间
MongoDB 不保证过期数据会在到期时立即被删除。一旦一个桶中的所有文档都过期,删除过期桶的背景任务将在下一次运行时删除该桶。单个桶可以覆盖的最大时间跨度由时间序列集合的 granularity 控制
| 粒度 | 覆盖时间跨度 | 
|---|---|
| "seconds"(默认) | 一小时 | 
| "minutes" | 24小时 | 
| "hours" | 30天 | 
删除过期桶的背景任务每60秒运行一次。因此,文档可能在文档到期、桶中所有其他文档到期以及运行背景任务之间的期间仍然存在于集合中。
由于删除操作的时间取决于您 mongod 实例的工作负载,过期的数据可能会在后台任务运行之间,即 60 秒周期之外存在一段时间。