转自:http://www.cnblogs.com/huangxincheng/p/5718038.html
现在我想大家对ttlIndex有了大概的认识了,下面我们看看怎么创建,我使用的GUI工具是robomongo,大家可以在官网上下载一下即可。。。然后我们
要查询一下https://docs.mongodb.com/manual/reference/method/db.collection.createIndex/#db.collection.createIndex,看看这种collection
怎么创建。
db.collection.createIndex(keys, options)
从这个options中的expireAfterSeconds参数来看,这个value是一个int,并且是以second为单位,然后我们可以看到,这个ttlIndex是需要建立在docment
的field上面的,然后我们继续往下看。
1
|
To
create a TTL index, use the db.collection.createIndex() method with the expireAfterSeconds option on a
field whose value is either
a date or an array that contains date values. |
从这句话中其实可以看到,这个field字段要么是date,要么是array中含有date字段,ok,看完这里,我们都明白了,接下来,我们创建一个简单的planeollection,
并且date的过期时间是2s,主要是用来测试一下嘛。。。
ok,其实就是这么简单,然后我们过60s之后再查看一下数据,可以看到,数据已经没有啦~~~
可能有些人就有疑问了,为什么这里要说最多60s之后再查看数据,当然是有原因的,因为mongod有一个background task,60s启动一次进行index scan,
如果过期,那么就会进行清除,不信的话,你可以看下官网的描述哦。