TTL集合支持mongodb对存储的数据进行失效时间设置,经过指定的时间段后、或在指定的时间点过期,集合自动被mongod清除。这一特性有利于对一些只需要保存一定时间的数据信息进行存储,比如机器产生的事件数据、日志、会话信息等。
Mongodb使用TTL索引特性来实现TTL集合。TTL通过一个后台线程读取索引中数据类型的值,然后清除过期的集合。
集合中的文档超过expireAfterSeconds关键字定义的时间后,该文档就变得过期了,会被自动删除。在创建TTL索引的时候,需要使用到关键字expireAfterSeconds,索引中对应的field的值的类型必须是date,或者对应的array包含date类型的值。
只能对单列索引创建TTL索引,组合索引不能是TTL索引。
1.经过指定的时间间隔后,集合失效
1
2
3
4
5
6
7
8
9
10
11
12
13
|
> db.log_events.createIndex({
"createdAt"
: 1},{expireAfterSeconds: 180}) #5分钟后过期
#插入文档
> db.log_events.
insert
({
"createdAt"
: new
Date
(),
"logEvent"
: 2,
"logMessage"
:
"Success!"
})
#查看
> db.log_events.find()
{
"_id"
: ObjectId(
"56e219ecf694a8d2cff60cca"
),
"createdAt"
: ISODate(
"2016-03-11T01:05:48.082Z"
),
"logEvent"
: 2,
"logMessage"
:
"Success!"
}
#5分钟后再次查看(已被清除)
> db.log_events.find()
>
|
2.指定时间点过期
将参数expireAfterSeconds设置为0,expireAt指定过期时间
1
2
3
4
5
6
7
|
> db.ttl.createIndex({
"expireAt"
: 1},{expireAfterSeconds:0})
#插入文档
> db.ttl.
insert
({
"createdAt"
: new
Date
(
'Mar 11, 2016 09:30:00'
),
"logEvent"
: 2,
"logMessage"
:
"Success!"
})
|
使用TTL时是有限制的:
-如果要索引的字段已经在其他索引中使用,不能创建TTL索引
-索引不能包含多个字段
-如果定义的字段不存在,则永不过期
-不能对capped集合创建TTL索引