本篇将延续时间序列集合的主题,重点讲解如何设置时间序列集合自动删除(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
要获取 expireAfterSeconds 当前值,使用 listCollections
命令:
db.runCommand( { listCollections: 1 } )
该命令查询结果为时间序列集合中一个包含 options.expireAfterSeconds 字段的文档。
cursor: {
id: <number>,
ns: 'test.$cmd.listCollections',
firstBatch: [
name: <string>,
type: 'timeseries',
options: {
expireAfterSeconds: <number>,
timeseries: { ... }
删除过期桶的任务每60秒执行一次。因此,在文档过期、桶中所有其他文档过期和后台任务运行之间的这段时间内,文档可能仍然保留在集合中。
由于删除操作的持续时间取决于 mongod 实例的工作负载,因此在后台任务运行之间的60秒周期之外,过期数据可能还会存在一段时间。
上一篇
MongoDB 用户大会世界巡演即将登陆中国