翻译或纠错本页面

通过设置TTL使集合中的数据过期

On this page

本文对MongoDB的 “存活时间” 或者叫作”TTL“的集合特性进行了介绍。TTL集合能让存储在MongoDB中的数据在指定的秒数后或在指定的时钟时间被 mongod 自动删除。

数据过期对某些类型的信息很有用,包括机器生成的事件数据、日志以及只需要存在一段有限时间内的会话信息。

一个特别的索引类型支撑了TTL集合的实现。TTL依赖一个在 mongod 中的后台线程,该线程读取索引中日期类型的值并从集合中删除过期的 documents

步骤

在(文档)创建之后一定的秒数删除文档。这样的TTL索引还会支持对于文档创建时间的查询。或者,

注解

The TTL index is a single field index. Compound indexes do not support the TTL property. For more information on TTL indexes, see TTL索引.

You can modify the expireAfterSeconds of an existing TTL index using the collMod command.

Expire Documents after a Specified Number of Seconds

为了使文档在一定的秒数后过期,在容纳BSON日期类型或BSON日期类型对象数组的值的字段上创建TTL索引 expireAfterSeconds 指定一个正的非零值。当被索引字段 [1] 指定的时间经过了 expireAfterSeconds 字段中的秒数时,文档将会过期。

例如,如下操作在 log_events 集合的 createdAt 字段创建了一个索引并指定 expireAfterSeconds 的值为 3600 以使过期时间为 createdAt 指定的时间之后的一小时。

db.log_events.createIndex( { "createdAt": 1 }, { expireAfterSeconds: 3600 } )

当向 log_events 集合添加文档时,设置 createdAt 字段为当前时间:

db.log_events.insert( {
   "createdAt": new Date(),
   "logEvent": 2,
   "logMessage": "Success!"
} )

当某文档的 createdAt 字段的值 [1] 晚于 expireAfterSeconds``中指定的秒数时,MongoDB会自动从 ``log_events 集合删除该文档。

[1](1, 2)

如果该字段包含一组BSON日期类型的对象,如果至少有一个BSON日期类型的对象晚于 ``expireAfterSeconds``中指定的秒数,数据过期。

参见

$currentDate 操作符

Expire Documents at a Specific Clock Time

为了使文档在一个确定的时钟时间过期,首先在一个容纳BSON日期类型或BSON日期类型对象数组的值的字段上创建TTL索引 expireAfterSeconds 指定为 0。对于集合中的每个文档,设置其被索引的日期字段为与文档过期的时间一致的值。如果被索引字段包含了一个过去了的日期,MongoDB认为该文档过期。

例如,如下操作在 log_events 集合的 createdAt 字段创建了一个索引并指定 expireAfterSeconds 的值 0

db.log_events.createIndex( { "expireAt": 1 }, { expireAfterSeconds: 0 } )

对于每个文档,设置 expireAt 的值与文档过期的时间一致。举例来说,如下的 insert() 操作添加了一个将在 2013年7月22号 14:00:00 过期的文档。

db.log_events.insert( {
   "expireAt": new Date('July 22, 2013 14:00:00'),
   "logEvent": 2,
   "logMessage": "Success!"
} )

MongoDB will automatically delete documents from the log_events collection when the documents’ expireAt value is older than the number of seconds specified in expireAfterSeconds, i.e. 0 seconds older in this case. As such, the data expires at the specified expireAt value.

←   TTL索引 唯一索引  →