I'm trying to make a search in a MongoRepository class between two dates, as I got in vscode MongoDB, but just got result using new ISODate:

db.getCollection('kidsClass').find({
    "openShift": {$gte:new ISODate("2023-12-10T17:00:00.501Z"),$lte:new ISODate("2023-12-10T19:00:00.501Z")}
 });

The data structure in Mongo Database is:

"openShift": { "$date": "2023-12-10T18:00:00Z" }

But if I do the search without ISODate, the result is empty:

db.getCollection('kidsClass').find({
    "openShift": {$gte:"2023-12-10T17:00:00.501Z",$lte:new "2023-12-10T19:00:00.501Z"}
 });

The same way in vscode, it just works using new ISODate like shown below, declaring the date inside:

    @Query("{ 'openShift': {$gte: new ISODate('2023-12-10T17:00:00.501Z'), $lte: new ISODate('2023-12-10T19:00:00.501Z')}}")
    List<ClassModel> findByShift(String ini, String fin);

The problem is that I need to make it dynamically, but when I try to change dates by position of arguments, it returns empty always:

    @Query("{ 'openShift': {$gte: new ISODate(?0), $lte: new ISODate(?1) }}")
    List<ClassModel> findByShift(String ini, String fin);

In the example above and the one below, the string type in the arguments was used trying to pass literally the value received without messing the date format using Date, but no success either:

    @Query("{ 'openShift': {$gte: ?0, $lte: ?1 }}")
    List<ClassModel> findByShift(String ini, String fin);

I tried a lot of ways like the one below that the type of arguments is Date, but now success anyway:

    @Query("{ 'openShift': {$gte: ?0, $lte: ?1 }}")
    List<ClassModel> findByShift(@DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") Date ini, @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") Date fin);

So the only way that worked for me in java was passing literally the date inside new ISODate at @Query expression (example given above), but as I said it has to be done dynamically to be used with different dates, according to the user needs.

If someone has a clue, I appreciate a lot, because I'm struggling a lot of days and no success till now.

Thanks in advance.

0

There are 0 best solutions below