1

I want to use Jongo for date queries. The user should be able to enter a string with the query, so I want to use the find method with a string. I am using groovy.

My code:

jongo.getCollection("mycollection").find("{birthday: {\$lt : ISODate(\"2012-11-23T00:13:00.000Z\")}}")

I get this exception:

java.lang.IllegalArgumentException: Cannot parse query: {birthday: {$lt : ISODate("2012-11-23T00:13:00.000Z")}}
Error |
at org.jongo.query.BsonQueryFactory.createQuery(BsonQueryFactory.java:162)
Error |
at org.jongo.Find.<init>(Find.java:47)
Error |
at org.jongo.MongoCollection.find(MongoCollection.java:84)
Error |
at org.jongo.MongoCollection.find(MongoCollection.java:80)

What am I doing wrong?

Peter
  • 1,011
  • 2
  • 16
  • 39

1 Answers1

3

Yep found the relevant line in the source code to confirm

"ISODate" has nothing to do with this, it's a JavaScript function name in the mongo shell.

Jongo is using the MongoDB Extended JSON standard for parsing. So you would do

`{ \$date: \"2012-11-23T00:13:00.000Z\" }`

instead.

Really, use the quotes the other way around to make it cleaner:

.find("{ 'birthday': { '$lt': { '$date': '2012-11-23T00:13:00.000Z' } } }")
Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
  • This works. Do you know if it is possible to convert a string field in mongodb to a date? For example, birthday is a string in my collection, but I want to treat it is a date – Peter Jun 23 '17 at 10:18
  • Is it possible to do date calculations with this syntax? – Peter Jun 23 '17 at 10:37
  • 1
    @Peter If you have a new question then [Ask a new Question](https://stackoverflow.com/questions/ask). But this is just JSON, so the real point is you can do you calculations and whatever structure changes you want in your normal code. Then you just serialize your other objects to JSON with this type of "key" name format. You don't do calculations in "strings". Which is all it is really. – Neil Lunn Jun 23 '17 at 10:43
  • You saved not only my day but days!! Thanks a ton – ersnh Dec 09 '19 at 18:56