Ram Viswanathan
Ram Viswanathan

Reputation: 201

java mongo create date

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

Answers (1)

Alex
Alex

Reputation: 46

Another approach - use standard Spring Data MongoDB auditing feature (assuming, your project is Spring based).

  1. Add spring-data-mongodb dependency
  2. Annotate your main class with @EnableMongoAuditing
  3. Add to your mongoDb entity class a field LocalDate createdDate
  4. Annotate this new field with @CreatedDate
  5. Profit. Every new saved entity will automatically get current date injected in this new field.

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

Related Questions