Reputation: 201
I have a java code that is inserting an object into a collection in Mongo DB. While I insert this new object (details of the object given below), I need to also insert a creation date. What's the best way to handle this? Since we have different time zones, I want to make sure that I am following the correct approach for saving and reading the date fields.
document structure: I need to have my java code create a system date that would insert the creation date into Mongo DB in a proper format.
{ "_id" : ObjectId("568ac782e4b0fbb00e4f1e45"), "cat" : "Abc", "name" : "testName" }
Please advise.
Upvotes: 1
Views: 1941
Reputation: 46
Another approach - use standard Spring Data MongoDB auditing feature (assuming, your project is Spring based).
spring-data-mongodb
dependency@EnableMongoAuditing
LocalDate createdDate
@CreatedDate
So, your main class will look like this:
@SpringBootApplication
@EnableMongoAuditing
public class SpringDataMongodbAuditingApplication {
public static void main(String[] args) {
SpringApplication.run(SpringDataMongodbAuditingApplication.class, args);
}
}
And your entity class will look like this:
@Document
public class Client {
@Id
private ObjectId id;
private String name;
@CreatedDate
private LocalDate createdDate;
// constructor, getters, setters and other methods here ...
}
Your repository interface has nothing special:
@Repository
public interface ClientRepository extends MongoRepository<Client, ObjectId> {
}
Upvotes: 2