Spring Data MongoDB how to assign expiration time programmatically

吃可爱长大的小学妹 提交于 2020-05-14 16:00:05

问题


I couldn't find in any of the Spring-Data documents, what is the way to assign expiration time to a document in MongoDB?


回答1:


You can do it using @Indexed annotation's expireAfterSeconds attribute over a field whose type is Date.Roughly:

@Document
public class SomeEntity {

    String id;

    @Field
    @Indexed(name="someDateFieldIndex", expireAfterSeconds=3600)
    Date someDateField;

   // rest of code here

}

Or by manipulating a MongoTemplate:

mongoTemplate
    .indexOps(SomeEntity.class)
    .ensureIndex(new Index().on("someDateField", Sort.Direction.ASC).expire(3600));



回答2:


Thanks, but does the whole document is expired and deleted or just the field?

According to the MongoDB Documentation https://docs.mongodb.com/manual/core/index-ttl/ The TTL index is used to remove documents from a collection.

So, the entire document will be deleted and not uniquely the field indexed.

Nb : The index has to be positioned on a Date Field, else the TTL will not be apply

regards



来源:https://stackoverflow.com/questions/43966601/spring-data-mongodb-how-to-assign-expiration-time-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!