我知道使用 Spring Data for MongoDB 您可以设置要删除的文档:
@Indexed(name = "ttl", expireAfterSeconds = 12)
private LocalDateTime expireAfterSeconds;
或
@Indexed(name = "ttl", expireAfter = "12s")
private LocalDateTime expireAfterSeconds;
这些文档将在注释中指定的时间后被删除,对于每个创建的文档都是相同的。
我想了解是否仍然可以创建 TTL 索引,但可以为每个文档计算该值。 (就像在 DynamoDB 中一样,您会以秒为单位通过纪元时间)
类似的东西
@Document("groceryitems")
public class GroceryItem {
@Id
private String id;
@Indexed(name = "deleteThisRecordAfter", expireAfter = "@checkActualValue")
private LocalDateTime expireAfter;
// or
@Indexed(name = "deleteThisRecordAfter", ttlIndex = true)
/*
* ttlIndex = true doesn't exist,
* but I would like to only have a TTL index and then provide a value for the field
* that mongod will use to determine when to delete the document.
*/
private LocalDateTime expireAfter;
public GroceryItem(String id, LocalDateTime expireAfter) {
super();
this.id = id;
this.expireAfter = expireAfter;
}
}
public persist(Item item) {
repository.save(new GroceryItem(item.getId(), getCorrectTTL(item.getExpirationDate(), item.getCategory())));
}
是的,这是可能的,尽管 Spring Mongo 数据没有记录(或者不是以我认为简单的方式记录)。
但是,MongoDB 文档中写了如何做到这一点,因为这不是 Spring data 的功能,而是 Mongo 的功能。您可以在这里查看:https://www.mongodb.com/docs/manual/tutorial/expire-data/#expire-documents-at-a-specific-clock-time
所以你需要在代码中做的是:
@Indexed(name = "ttl", expireAfterSeconds = 0) // this is the trick, as Mongo will consider expired any timestamp in the past.
private LocalDateTime expireDate;
然后在您的应用程序代码中,您只需指定特定文档到期的时间戳:
var e = new Entity();
e.setExpireDate(LocalDateTime.now().plusSeconds(howManySecondsIWantToKeepThisDoc));
所以,是的,这种方法是可能且可行的。