1

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.

rwachter
  • 23
  • 3
  • It's because of the way you are populating `field2`. Populate it as `obj.asText()` where `obj` refers to the object in the collection. – Arvind Kumar Avinash Dec 12 '22 at 19:51
  • It's not possible for us to do that. This is a Mongo Date field populated from a long. – rwachter Dec 12 '22 at 20:33
  • `field2` in the document is a sub-document (or an object). It has two fields and one of them is a _Date_ type. In general, you map the document's sub-document to an inner class and the date field to a Java's `LocalDateTime` or `java.util.Date`. In your case, it is mapping to a date data type. You can possibly convert it to a number by applying a `getTime()` method of date. – prasad_ Dec 13 '22 at 03:30
  • A solution I have for now is similar to that. I recursively work through the Document to find any Date objects and covert them to longs. I've updated the post with my code and what I would prefer to happen. – rwachter Dec 13 '22 at 15:09

0 Answers0