简体   繁体   中英

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 ?

使用java.util.Date是使用Jongo查询日期的标准方法:

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

通过传递多个参数进行查询 -

jongoCollection.find("{date : { $gte : #, $lte : # }}", new Date(1234567890), new Date(1234567890))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM