1

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.

3
  • you have the $currentDate operator Commented Jan 13, 2016 at 20:33
  • 1
    Java ObjectId has a getDate() method which returns insert data Commented Jan 13, 2016 at 21:25
  • Thank you very much for your response. It worked for me. Commented Jan 14, 2016 at 23:39

1 Answer 1

2

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> {

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.