Query MongoDB by date in Java

I am trying to query mongodb for documents where "date" is two dates. Sample data:

{
        "_id" : ObjectId("4fad0af6709fbc1d481c3e05"),
        "ID" : NumberLong("200930746205085696"),
        "text" : "Forgot my charger...:(",
        "date" : ISODate("2012-06-14T10:49:57Z"),
        "sentiment" : "NEG"
}

My Java code is:

DBCursor cursor = null;
DB db = connect();

    Date startDate = new Date(System.currentTimeMillis() - (long)(numOfTimePeriods+1)*time);
    Date endDate = new Date(System.currentTimeMillis() - (long)numOfTimePeriods*time);
    DBObject query = new BasicDBObject();
    query.put("date", new BasicDBObject("$gt", startDate).append("$lte", endDate));

    cursor = db.getCollection("status").find(query);

but the cursor object has no results.

The request object is as follows:

{ "date" : { "$gt" : { "$date" : "2012-05-15T00:16:15.184Z"} , "$lte" : { "$date" : "2012-06-14T10:16:15.184Z"}}}

I suspect that the problem is presenting the date in the database. Any suggestions on this?

+5
source share
2 answers

This $ date view is just a toString view in the Date Java driver. It uses the strict JSON / BSON representation, not the extended BSON 10gen, where values ​​can be objects represented in the same way as in the shell. You should not try to query the shell using toString output like this because it will not work in many cases.

+1
source

?

db.foo.find( { $and: [ { date: { $gt: startDate } }, {date : { $lt: endDate} }  ] } )
-1

All Articles