2014년 12월 28일 일요일

Date Range Query with java driver is not returning any results

Using mongodb java driver to do the range query on dates.

Had the following data under collection named "TestData".
{
    "_id" : ObjectId("5491d8c2bd6e045d05a40b98"),
    "eventId" : "1",
   "createdDate" : ISODate("2014-12-18T00:37:23.810Z")
}

Formulated the following db query through java driver, but it is not returning any results. 
db.TestData.aggregate({ "$match" : { "createdDate" : { "$gte" : { "$date" : "2012-12-18T00:37:23.810Z"} , "$lte" : { "$date" : "2015-02-18T00:37:23.810Z"}}}});

Tested on both mongodb(2.6.50  and mongo driver (2.12.3, 2.13.0-rc0)



Can you show the Java code for running the problematic query? The query is correctly formatted in strict mode MongoDB extended JSON, and it matches the example document. Where did the query come from? Java driver logging?



Hi Will,

Used '"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"  format to store the dates into db.

Using the following code for querying. date1 and date2 are java.util.date objects.
   queryBuilder.put(searchKey).greaterThanEquals(date1).lessThanEquals(date2);

public List query(Criteria criteria, String storeName) {
   List<DBObject> dbCriterias = getCriterias(criteria);
   printQuery(dbCriterias, storeName);
   AggregationOutput output = dbCollection.aggregate( dbCriterias);   List results = output.results();
   return results;
}


// Prints the query so that it can be verified in client tools
//Date queries may not work in some tools if they support only javascript as they need isodate instead of the generated one.
public void printQuery(List<DBObject> criterias, String storeName) {
         
if(criterias != null && !criterias.isEmpty() ) {
             
System.out.println("\n pipelineOps:" + " db." + storeName +".aggregate(" +
                criterias
.toString().substring(1, criterias.toString().length() - 1 ) + ");");
         
}
 
}



You say:
Used '"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"  format to store the dates into db.
But that's a string and not a date so it won't match a query on date range.


댓글 없음:

댓글 쓰기