Last updated: 2024-03-19
CreatedDate and LastModifiedDate in Spring Data MongoDB
It is often of interest to add the date of creation and last modification to a document. Spring Data MongoDB provides excellent support for this by enabling auditing.
First, we need to extend the config of our Spring Boot application. While for relational databases @EnableJpaAuditing
is available, for Spring Data MongoDB we use the annotation @EnableMongoAuditing
. @PrePersist
and @PreUpdate
is not available for MongoDB - auditing is the best option we have here.
Extending our configuration for auditing
By specifying the DateTimeProvider
we can also use OffsetDateTime
as a field type. Otherwise only Long
, java.util.Date
as well as joda time types would be available. Details about the converters can be found in this article. With this configuration in place, we can now enable @CreatedDate
and @LastModifiedDate
on our documents.
We also need a @Version
field in our documents, otherwise there will be problems in combination with the Id field. If the id is pre-filled by our application, auditing assumes that the document already existed in the database and @CreatedDate
is not set. With the version field however, the life cycle of our entity is correctly captured.
In Bootify's Free plan you can opt for adding dateCreated and lastUpdated fields for all your entities in the database settings. It will enabled auditing and provide a DateTimeProvider
to support OffsetDateTime
as a field type.
Further readings
Spring Data MongoDB auditing documentation