javaspringmongodbmongo-collection

How to receive Date from Mongodb without NumberLong or Date Wrapper in Java


currently, I'm developing a Java/Spring App where I save and provide JSON from/to clients.

I've stores my Date information as a Unix timestamp in a millisecond. Now MongoDB stores this automatically as

"StartTime": {"$numberLong": "1549640550000"}

when I insert

"StartTime": 1549640550000

I've also read that this happens with $Date instead of $numberLong when I use the iso8601 format.

Is it possible to read the Time information from MongoDB without this Wrapper Information in my query result?

It seems pretty uncomfortable to me to handle/remove the information te receive the plain TimeStamp Information.

EDIT: When I use document.toJSON ( I know it's deprecated) I get

"StartTime": {"$numberLong": "1549640550000"}

when I use document.toString() I get TimeStamp=Document{StartTime=1549554150000}


Solution

  • You need to build a JSON serializer which can convert NumberLong to Long. You can use the following settings and pass in Document.toJson() as a parameter and get the expected output.

    JsonWriterSettings settings = JsonWriterSettings.builder()
                .int64Converter((value, writer) -> writer.writeNumber(value.toString())).build();
    
    document.toJson(settings); // The output would contain simple long value