Spring Data MongoDB how to assign expiration time programmatically

前端 未结 2 1505
春和景丽
春和景丽 2021-01-17 15:45

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

2条回答
  •  有刺的猬
    2021-01-17 16:45

    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));
    

提交回复
热议问题