2

I am trying to use make my own query for a mongo Repository:

@Repository
public interface LogEntryRepository extends MongoRepository<LogEntry,String> {

    @Query("{'created_at' : {{ $gte: ISODate(?0)},{$lt: ISODate(?1)}}, " +
        "$or: [{'site': {$regex: ?2}}, {'login': {$regex: ?2}}, {'ip': {$regex: ?2}} ]" +
        "}")
    public Page<LogEntry> findByDateTimeBetweenAndCriteria(String isoStartDate, String isoEndDate, String searchTerm, Pageable page);

}

What I'd like to achieve is searching though dated logs with a keyword. The above complains about a parse error:

        Caused by: com.mongodb.util.JSONParseException: 
    {'created_at' : { $gte: ISODate("_param_0"), $lt: ISODate("_param_1")}, $or: [{'site': {$regex: "_param_2"}}, {'login': {$regex: "_param_2"}}, {'ip': {$regex: "_param_2"}} ]}
                            ^

If I replace the ISODate(?0) with simply ?0 it produces Page 1 of 0 containing UNKNOWN instances

The Strings isoStartDate & isoEndDate are produced from java.util.Date and look like this 2017-06-27T00:00:00.000Z

How do I get my date in there?

OrangePot
  • 1,053
  • 2
  • 14
  • 38

1 Answers1

5

ISODate is a Mongo shell construct to create a BSON date and definitely not valid JSON, which is what I believe your error is complaining about.

Try replacing the above ISODate calls with { '$date' : '?0' } and { '$date' : '?1' } as suggested in this answer. All the strings should probably need to be surrounded in single quotes.

Kdawg
  • 1,508
  • 13
  • 19
  • Even this causes JSON parse errors: `@Query("{'created_at': {$date: ?0}}")` with ?0 = 2017-06-28T00:00:00.000Z (String). Any thoughts? – OrangePot Jul 27 '17 at 16:48
  • @OrangePot You should have double quotes around `"$date"` – Kdawg Jul 27 '17 at 16:49
  • It doesnt seem to make a difference whether I put escape \" around `$date`. This little symbol `^` is under `?0` when the error message is shown – OrangePot Jul 27 '17 at 16:54
  • @OrangePot: Hmm... You could try single quotes around both the `$date` and the `?0`. – Kdawg Jul 27 '17 at 16:56
  • My query now looks like this and it fixed the parse error `@Query("{'created_at': {$gte: {$date: '?0'}}}")` (Single quotes around the `?0`) and `?0` is a `java.util.Date` – OrangePot Jul 27 '17 at 17:09
  • Hey Kdawg! I'm having a very similar problem, however, your answer doesn't seem to work on my situation. Do you mind taking a look on my [question](https://stackoverflow.com/questions/56862718/making-date-queries-on-mongodb-using-json-on-springdatamongodb)? Maybe you'll be able to help me. Tks – Tin Megali Jul 03 '19 at 04:00