Mongo ISODate query in Java
Asked Answered
I

2

13

I have a mongo query to be executed :

query = { "dateField" : { "$gte" : ISODate('2011-11-10T07:45:32.962Z')  } }

When I do a db.Collection.find(query) on the mongo shell, I am able to retrieve the results.

How could I query this using Java ? I tried constructing a String based on the Date parameter. But in the process of building the String, it eventually gets passed as "ISODate('2011-11-10T07:45:32.962Z')" instead of ISODate('2011-11-10T07:45:32.962Z') (without the surrounding quotes).

What would be the best way to construct this query using the Java API ?

Thanks !

Inspectorate answered 1/2, 2012 at 5:18 Comment(1)
Do not use strings. Strings are not dates.Sodium
S
22

Use a regular Java Date--also I recommend the QueryBuilder:

Date d = new Date(); // or make a date out of a string...
DBObject query = QueryBuilder.start().put("dateField").greaterThanEquals(d).get();
Smutty answered 1/2, 2012 at 5:32 Comment(1)
Yes, that's the Java equivalent of ISODate(). Try running the query, rather than looking at the toString().Smutty
M
7

I have search lot and spend more than hour in finding how to get data when having ISODate in mongo model.

As the default constructor for date is deprecated so it was not working in my case.

BasicDBObject searchQuery = new BasicDBObject("_id" , 1);
try {
        searchQuery.append("timestamp",BasicDBObjectBuilder.start( "$gte",new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS\'Z\'").parse("2015-12-07T10:38:17.498Z")).get());
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
Multiplier answered 8/12, 2015 at 15:52 Comment(2)
Is this an answer or a comment? If it's an answer, please edit it to clarify how it addresses the question.Mainsheet
This is answer, I am telling that the simple Date not works as it is deprecated and this thing SimpleDateFormat was working fine in my case.Multiplier

© 2022 - 2024 — McMap. All rights reserved.