spicybanjo
spicybanjo

Reputation: 81

Spring Boot and MongoDB - how to save date

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);
}
}

Upvotes: 8

Views: 38201

Answers (3)

user641887
user641887

Reputation: 1576

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"));
    }
}

Upvotes: 1

user8369145
user8369145

Reputation:

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.

Upvotes: 4

ashutosh
ashutosh

Reputation: 81

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 .

Upvotes: 0

Related Questions