Docs 菜单

Docs 主页开发应用程序MongoDB Manual

设置时间序列集合 (TTL) 的自动删除

在此页面上

  • 对集合启用自动删除
  • 更改 expireAfterSeconds 参数
  • 检索当前值 expireAfterSeconds
  • 禁用自动删除
  • 行为
  • 删除操作的时机

创建时间序列集合时,可以使用 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 参数值,请发出以下 collMod 命令:

db.runCommand({
collMod: "weather24h",
expireAfterSeconds: 604801
})

要检索 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 控制:

granularity
覆盖的时间跨度
"seconds" (默认)
一小时
"minutes"
24 小时
"hours"
30天

删除过期存储桶的后台任务每 60 秒运行一次。因此,在文档到期、存储桶中所有其他文档到期和后台任务运行之间的这段时间内,文档可能会保留在集合中。

由于删除操作的持续时间取决于 mongod 实例的工作负载,因此过期数据可能会在后台任务运行之间的 60 秒以后持续一段时间。

← 列出数据库中的时间序列集合