1 实现原理(TTL索引)
TTL索引是一些特殊的索引,MongoDB可以在一段时间后使用它自动从集合中删除文档。这对于某些类型的信息比如机器生成的事件数据,日志和会话信息是合适的,因为这些信息只需要在有限的时间内保留在数据库中。
官方文档:https://docs.mongodb.com/manual/tutorial/expire-data/
1.1 mongodb内部实现原理
一个特殊的TTL索引属性支持TTL集合的实现。TTL功能依赖后台线程mongod读取索引中的日期类型值并从集合中删除过期的文档。根据网络资料,mongodb 是60秒check一次是否过期。
1.2 使用条件
创建TTL索引,请在(值为日期或包含日期值的数组 )的字段上使用该 db.collection.createIndex()方法创建索引,且TTL索引必须是单个字段索引。复合索引不支持TTL属性。
2 使用
TTL索引有两种使用方式
- 在指定的秒数后删除该文档
- 在特定时间过期删除文档
2.1 在指定的秒数后删除该文档
当设定的expireAfterSeconds 过期时间在指定时间字段的基础上已经过完,该文档将会过期。
db sample:
db.log_events.createIndex( { "createdAt": 1 }, { expireAfterSeconds: 3600 } )
db.log_events.insert( {
"createdAt": new Date(),
"logEvent": 2,
"logMessage": "Success!"
} )
MongoDB will automatically delete documents from the log_events collection when the document’s createdAt value [1] is older than the number of seconds specified in expireAfterSeconds.
“createTime”: 1 —字段名称 expireAfterSeconds: —过期时间(单位秒)
2.2在特定时间过期删除文档
特定时间过期文档,请首先在保存BSON日期类型值的字段或BSON日期类型对象数组的字段上创建TTL索引,并指定expireAfterSeconds值为0。如果当前时间超过索引时间,文档将会过期。
db sample:
db.log_events.createIndex( { "expireAt": 1 }, { expireAfterSeconds: 0 } )
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.
“expireAt”: 1 -过期时间字段 expireAfterSeconds: —设定为指定时间过期
3 nodejs 实现
Mongoose 提供了两个API
- Schema.prototype.index()
- Model.createIndexes()
http://mongoosejs.com/docs/api.html#createindexes_createIndexes
3.1在指定的秒数后删除该文档
指定的字段必须为date 类型。
创建collocation时 创建TTL索引 该collocation下 所有新的document都会创建后到过期时间那会自动删除
var MessagesModel = db.model('message', MessagesSchema);
MessagesModel.createIndexes(MessagesSchema.index({time:1}, {expires:60*2}), function(err, info){
if(err) console.error(err);
console.info(info);
});
索引字段:time
过期时间:expires 120秒
3.2 指定到期时间
创建collocation时 创建TTL索引 该collocation下 指定某个字段作为过期时间,现实时间大于过期时间时将会自动删除该数据。
var MessagesModel = db.model('message', MessagesSchema);
MessagesModel.createIndexes(MessagesSchema.index({expires:1}, {expireAfterSeconds:0}), function(err, info){
if(err) console.error(err);
});
索引字段(过期时间字段):expires
过期时间:expireAfterSeconds 0秒(设定为指定时间过期)
参考链接:https://blog.csdn.net/jianlong727/article/details/54631124