MongoDB expireAfterSeconds的用法(附带实例)
MongoDB 数据库在创建天气测量值时间序列集合时,可以使用 expireAfterSeconds 参数设置自动删除超过指定秒数的文档,具体代码如下:
在上面的代码中,过期阈值为 timeField 字段值加上指定的秒数。例如,考虑天气测量值时间序列集合中的以下文档:
上面的文档将于 2024-08-18T00:00:00.000Z 时间后在数据库中过期,一旦存储桶中的所有文档都过期,删除过期存储桶的后台任务就会在下一次运行期间删除该存储桶。
设计人员如果要在集合中启用自动删除现有时间序列集合的文档,可以使用以下 collMod 命令:
设计人员如果要更改 expireAfterSeconds 参数值,也可以发出以下相同的 collMod 命令:
设计人员如果要检索 expireAfterSeconds 的当前值,可以使用 listCollections 命令:
结果文档包含时间序列集合的文档,其中包含 options.expireAfterSeconds 字段:
设计人员如果要禁用自动删除,可以使用 collMod 命令将 expireAfterSeconds 参数设置为 off,具体代码如下:
db.createCollection( "weather", { timeseries: { timeField: "timestamp", metaField: "metadata", granularity: "hours" }, expireAfterSeconds: 86400 } )
在上面的代码中,过期阈值为 timeField 字段值加上指定的秒数。例如,考虑天气测量值时间序列集合中的以下文档:
{ "metadata": { "sensorId": 6688, "type": "temperature" }, "timestamp": ISODate("2024-08-18T00:00:00.000Z"), "temp": 12 }
上面的文档将于 2024-08-18T00:00:00.000Z 时间后在数据库中过期,一旦存储桶中的所有文档都过期,删除过期存储桶的后台任务就会在下一次运行期间删除该存储桶。
设计人员如果要在集合中启用自动删除现有时间序列集合的文档,可以使用以下 collMod 命令:
db.runCommand({ collMod: "weather", expireAfterSeconds: 604801 })
设计人员如果要更改 expireAfterSeconds 参数值,也可以发出以下相同的 collMod 命令:
db.runCommand({ collMod: "weather", 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: "weather", expireAfterSeconds: "off" })MongoDB 数据库不保证过期数据会在过期后立即删除,一旦一个存储桶中的所有文档都过期,删除过期存储桶的后台任务就会在下一次运行期间删除该存储桶。