Mongodb通常会被用来存储缓存数据或大尺寸、低价值的数据,对于这些类型的数据,数据量往往非常大,如果不定期清理,不但会影响性能,也会浪费大量的系统资源。
db.log_events.createIndex( { "createTime": 1 }, ---字段名称 { expireAfterSeconds: 60*60 } ) ---过期时间(单位秒)
db.runCommand({ collMod: "log_events", ---集合名 index: { keyPattern: { createTime: 1 }, ---createTime为具有TTL索引的字段名 expireAfterSeconds: 7200 ---修改后的过期时间(秒) }})
注:上面的createTime字段就不需要再有TTL索引了,这个expireTime的时间就需要在插入时指定上 db.log_events.createIndex( { "expireTime": 1 }, ---字段名称 { expireAfterSeconds: 0 } ) ---过期时间(单位秒) db.log_events.insert( { "expireTime": new Date('Jan 22, 2019 23:00:00'), ---插入文档时指定自动删除时间 "logEvent": 2, "logMessage": "Success!"} )
Document document = new Document(); document.append("createTime",1); IndexOptions indexOptions = new IndexOptions(); indexOptions.expireAfter(300L,TimeUnit.SECONDS); this.mongoTemplate.getCollection("test").createIndex(document,indexOptions);
使用spring-data-mongodb 1.7.0中的 BasicDBObject bson = new BasicDBObject(); bson.append("createTime",1); BasicDBObject options = new BasicDBObject(); options.append("expireAfterSeconds",7200); this.mongoTemplate.getCollection("test").createIndex(bson,options);
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对自学php网的支持。如果你想了解更多相关内容请查看下面相关链接
查看更多关于Mongodb设置TTL索引自动清除数据与过期数据的方法的详细内容...