8

I've followed the Spring.io guide for accessing MongoDB data with rest (https://spring.io/guides/gs/accessing-mongodb-data-rest/) and can save documents into mongo.

When I try to add a date field into the POJO and set the date as a new Date() object, it just saves the value as null when it saves to mongo.

I've created an extremely basic @RestController which is working fine (passes in the request body, and saves it down using my MongoRepository class), saving documents via the rest console. I tried creating a new date in here and setting it before saving it down to Mongo but this gives me something like "createdDate": 1472394366324.

I can save dates as a string into Mongo, but what I want is to be able to save dates in the date format so I can query them with a basic 'date between' query (so something like this, the exact format doesn't matter much - "date" : ISODate("2014-02-10T10:50:42.389Z"). I can write the queries to get values via parameters, but to get the 'date between' query working I need to be able to store date values into Mongo.

What is the easiest way to accomplish this?

Edit:

Pojo class -

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.format.annotation.DateTimeFormat;

import java.util.Date;

@Document(collection = "Musicians")
public class Musician {

@Id
private String id;

private String firstName;
private String lastName;

@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
private Date createdDate = new Date();

public Musician() {}

public Musician(String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
    //createdDate = new Date();
}

public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

public Date getCreatedDate() {
    return createdDate;
}

public void setCreatedDate(Date createdDate) {
    this.createdDate = createdDate;
}
}

The RestController class -

@RestController
@RequestMapping(value = "/musicians")
public class MusicianController {

@Autowired
MusicianRepository musicianRepository;

@Autowired
MongoTemplate mongoTemplate;

@RequestMapping(method = RequestMethod.POST, value = "")
public ResponseEntity<HttpStatus> createMusician(@RequestBody Musician musician) {
    Musician musicianIn = musician;

    musicianRepository.save(musicianIn);

    return new ResponseEntity(HttpStatus.ACCEPTED);
}

@RequestMapping(method = RequestMethod.GET, value = "")
public ResponseEntity<List<Musician>> getMusicians() {
    List<Musician> musicians = musicianRepository.findAll();

    return new ResponseEntity<List<Musician>>(musicians, HttpStatus.OK);
}
}
2
  • Uou can try to add the @CreatedDate annotation to the attribute of your POJO for example: class MyObject{ @CreatedDate Date date; } Commented Aug 28, 2016 at 15:47
  • this doesn't seem to change anything. I've added the annotation, and if i assign new Date() to my createdDate field it is null in mongo, and if i call the setter in the rest endpoint before saving to mongo it gives me a number like the one above. Am i supposed to do something else to get it working? Why does setting a date in the pojo constructor create a null value? Commented Aug 28, 2016 at 16:45

3 Answers 3

4

The most common way of using created/modified dates is by annotation @CreatedDate/@ModifiedDate. For enabling it, you have to use @EnableAuditing annotation somewhere next to @Configuration(or in the main Application file). If you prefer less annotations, you can just use java8 LocalDateTime class.

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

Comments

1

I tried this in my local mongodb and it works.

Can you try the following;

package com.mongo.examples;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.bson.BsonDocument;
import org.bson.Document;
import org.bson.conversions.Bson;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;

public class MongoDateTest {

    public static void main(String args[]){

        MongoClient mongoClient = new MongoClient("localhost",27017);
        MongoDatabase database = mongoClient.getDatabase("testdates");

        MongoCollection<Document> collection = database.getCollection("dts");
        collection.drop();
        List<Document> insertList = new ArrayList<Document>();
        Date date = new Date();
        Document document = new Document().
                append("_id", 20).append("date",date);
        insertList.add(document);
        collection.insertMany(insertList);
        System.out.println(collection.count());
        MongoCursor<Document> doc = collection.find(new Document("date", date)).iterator();
        System.out.println(doc.next().getDate("date"));
    }
}

12 Comments

i think this works as a basic java to mongo implementation, but is there a way to do it as part of the POJO? from what i can tell i'm supposed to write my endpoints to take in the parameters we want to set from the request body (in JSON) which will be in the form of the object we want to save down and should map directly to my POJO. Then i can do MyPojoClass myPojo = whateverOurRequestBodyIsCalled, and then call myMongoRepositoryClass.save(myPojo), and return a HttpStatus.ACCEPTED.
If i do it the way you have it above, will i have to remap all of the POJO fields to a document and save it down, or can i edit it and add in the date? If that is possible, is that what i SHOULD be doing? Apologies if these are silly questions.
try this, in your pojo where you have defined the date field add this annotation above the date field. something like ...@DateTimeFormat(iso = ISO.DATE_TIME) private Date createdDate; //getter and setter methods .. now call your pojo by setting the date as java.util.date and spring data would take care of converting that java.util.date to ISO date when you save. HTH..
ugh, i can't seem to get it. I've tried the @DateTimeFormat annotation exactly as you have it above. If i set createdDate = new Date() in the POJO constructor, i still get null. If i call the setter in the endpoint before saving, i get "createdDate": 1472405549532, and if i simply set createdDate = new Date() when i assign the variable in my POJO directly under the annotation i get the same. I thought this final solution might solve it but no. I'm completely baffled by this.
are u sure u are importing java.util.date and not java.sql.date ? can you share your code ?
|
0

this happen because mongo db store the date in UTC format which is no of miliseconds you can check out the mongodb https://docs.mongodb.com/manual/reference/method/Date/

you have to convert it to your local time zone date .

1 Comment

To keep local date time (with a separate timezone property) in Mongo database, I used the technique described by Chamindu at chamindu.dev/posts/localdatetime-spring-mongodb. Just make sure to extend AbstractMongoClientConfiguration instead of AbstractMongoConfiguration as he indicates.

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.