user3105453
user3105453

Reputation: 1981

Document in MongoRepository not deleted with 'expireAfterSeconds'

I would like my MongoRepository in Spring Boot to automatically delete documents at a certain point in time after creation. Therefore I created the following class:

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;

public class MyDocument {
    @Id
    private String id;
    @Indexed
    private String name;
    @Indexed(expireAfterSeconds = 0)
    private LocalDateTime deleteAt;
}

Then, I save it in the Spring Boot MongoRepository:

MyDocument doc = modelMapper.map(myDocumentDto, MyDocument.class);
LocalDateTime timePoint = LocalDateTime.now();
timePoint = timePoint.plusMinutes(1L);
doc.setDeleteAt(timePoint);
docRepository.save(doc);

I periodically query the repository and would assume that after one minute, the document will not be there anymore. Unfortunately, I get the document every time I query and it is never deleted.

What am I doing wrong?

The document is persisted as follows (.toString()):

MyDocument{id='5915c65a2e9b694ac8ff8b67', name='string', deleteAt=2017-05-12T16:28:38.787}

Is MongoDB possibly unable to read and process the LocalDateTime format? I'm using org.springframework.data:spring-data-mongodb:1.10.1.RELEASE, so JSR-310 should already be supported as announced in 2015 here: https://spring.io/blog/2015/03/26/what-s-new-in-spring-data-fowler

Upvotes: 1

Views: 3250

Answers (1)

user3105453
user3105453

Reputation: 1981

I could fix the issue:

First of all, java.time.LocalDateTime is no problem with Spring Data / MongoDB. For clarification, add a name to an index, e.g. @Indexed(name = "deleteAt", expireAfterSeconds = 0). This step might not be needed though. However, adding the @Document annotation helped a lot:

@Document(collection = "expiringDocument")

When I delete the whole collection while my application is running, a new document insert will create the collection again but without the indexes. To ensure indexes are created, restart the application.

Upvotes: 4

Related Questions