Issue retrieving an ISODate field from MongoDB in the correct format

136 Views Asked by At

We are running into issues retrieving MongoDB document using Spring JPA as it relates to MongoDB date field. Here is a document

{
    "field1": "some value",
    "field2": {
        "field2sub1": "some value",
        "field2datefield": ISODate(1234567890)
    }
}

Java object:

@Data
class Dto {
    private String field1;
    private JsonNode field2;
}

Once we retireve the data, the Dto.field2 looks as follows:

{
    "field2sub1": "some value",
    "field2datefield": {$date: "2022-01-01....."}
}

The conversion is done correctly, except for what I need is

{
    "field2sub1": "some value",
    "field2datefield": 1234567890
}

without {$date: ....}.

The data is retrieved using this code:

List<Dto> eventRtrs = mongoTemplate.find(query, Dto.class, "collection_name")

Is there a way to specify that date fields need to be retrieved as a long or a formatted date and not as {$date ...} object?

UPDATE:

Potential solution I found was to recursively search the Document for any Date objects and convert them to Longs.

private void documentIterator(Map<String, Object> map) {
    for(Map.Entry<String, Object> entry : map.entrySet()) {
        // if the value is another map, search one level deeper
        if (entry.getValue() instanceof Map) {
            documentIterator((Map<String, Object>) entry.getValue());
        }
        // if the value is a Date, change it to a Long
        else if(entry.getValue() instanceof Date) {
            entry.setValue(((Date) entry.getValue()).getTime());
        }
    }
}

Ideally though, I would be able to have the ObjectMapper do this conversion when it is converting the Document to a JsonNode to avoid this traversal.

0

There are 0 best solutions below