javamongodbdatejongo

Querying for date using jongo driver for mongo


I use jongo driver to connect to my mongoDB .

The syntax for querying - for ex, some age less than 18 - is

collection.find("{age: {$lt : 18}}");

but how to query for a date ?

In the mongoDB the date key value pair is stored like

{"date" : ISODate("2012-11-23T00:12:23.123Z")}

so I tried the following:

collection.find("{date: {$lt : ISODate(\"2012-11-23T00:13:00.000Z\")}}");

but I get this exception while running the java code :

Exception in thread "main" java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58)
Caused by: java.lang.IllegalArgumentException: {dateLastSeen: {$lt: ISODate("2012-11-23T00:13:00.000Z")}} cannot be parsed
        at org.jongo.query.Query.convertToDBObject(Query.java:33)
        at org.jongo.query.Query.<init>(Query.java:26)
        at org.jongo.query.QueryFactory.createQuery(QueryFactory.java:38)
        at org.jongo.Find.<init>(Find.java:42)
        ... 10 more
Caused by: com.mongodb.util.JSONParseException:
{dateLastSeen: {$lt: ISODate("2012-11-23T00:13:00.000Z")}}
                     ^
        at com.mongodb.util.JSONParser.parse(JSON.java:198)
        at com.mongodb.util.JSONParser.parseObject(JSON.java:231)
        at com.mongodb.util.JSONParser.parse(JSON.java:195)
        at com.mongodb.util.JSONParser.parseObject(JSON.java:231)
        at com.mongodb.util.JSONParser.parse(JSON.java:195)
        at com.mongodb.util.JSONParser.parse(JSON.java:145)
        at com.mongodb.util.JSON.parse(JSON.java:81)
        at com.mongodb.util.JSON.parse(JSON.java:66)
        at org.jongo.query.Query.convertToDBObject(Query.java:31)

So I think, that dates are not to be plainly converted to the corresponding string, but the syntax to search using date is different.

Anybody with jongo knowledge who can help ?


Solution

  • Using java.util.Date is the standard way to query for date with Jongo:

    collection.find("{date: {$lt : #}}", new Date(2012, 11, 30));