user123
user123

Reputation: 577

How to use $dateFromString in Spring MongoDB?

In my document, the date field is a string "date": "01/08/2018". How can I convert it to Date object in Spring MongoDB to able to use comparator operators like "gte, lte" to other date object.

I tried:

project()

   .and(DateOperators.DateFromString.fromStringOf("date")).as("date")

It just works with fields whose format is yyyy-MM-dd, and of course I ended up with:

'Error parsing date string '26/10/2016'; 0: Unexpected character '2'

How can I pass the pattern or Is there another way to get the my goal?

Upvotes: 1

Views: 2619

Answers (1)

Christoph Strobl
Christoph Strobl

Reputation: 6736

The format option has been added to $dateFromString in MongoDB Version 4 and is currently missing in Spring Data MongoDB. I've opened DATAMONGO-2047 to address the issue.
Meanwhile you may try the following to add it manually.

project().and(context -> {

    Document doc = DateFromString.fromStringOf("date").toDocument(context);
    doc.get("$dateFromString", Document.class).put("format", "dd/mm/yyyy");
    return doc;
}).as("date");

Upvotes: 2

Related Questions