I couldn't find in any of the Spring-Data documents, what is the way to assign expiration time to a document in MongoDB?
Asked
Active
Viewed 2.0k times
2 Answers
24
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));

Ori Dar
- 18,687
- 5
- 58
- 72
-
2Thanks, but does the whole document is expired and deleted or just the field? – ArsenalFan May 15 '17 at 18:33
-
2Its always the whole document – Santosh b Aug 11 '20 at 11:39
-
this does not work. the collection will not be a timeseries. – Sourajit Basak Dec 27 '22 at 12:19
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

mca
- 85
- 1
- 9