Bogdan Emil Mariesan
Bogdan Emil Mariesan

Reputation: 5647

MongoTemplate find by date conversion

I am trying to convert the following query:

{ "cd" : { "$lte" : ISODate("2013-06-30T09:12:29Z") , "$gte" : ISODate("2013-06-11T09:12:29Z")}}

To use with MongoTemplate and Query.

At the moment i am doing and approach like:

 Query query = new Query();
 query.addCriteria(Criteria.where("cd").lte(request.getTo()).gte(request.getFrom()));
 mongoTemplate.find(query,MyDesiredEntity.class)

But the query above returns no results when the first one returns around 15 which it should(request.getTo and request.getFrom are java.util.Date).

Is there a way to achieve this with org.springframework.data.mongodb.core.query.Query

Upvotes: 6

Views: 9337

Answers (1)

Trisha
Trisha

Reputation: 3931

I got this to work by reversing the lte and gte calls. I wrote a test to show it working:

@Test
public void shouldBeAbleToQueryBetweenTwoDates() throws Exception {
    // setup
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'");

    MongoTemplate mongoTemplate = new MongoTemplate(new Mongo(), "TheDatabase");
    DBCollection collection = mongoTemplate.getCollection("myObject");
    // cleanup
    collection.drop();

    // date that should match
    Date expectedDate = dateFormat.parse("2013-06-12T00:00:00Z");
    collection.insert(new BasicDBObject("cd", expectedDate));
    // date that should not match (it's last year)
    collection.insert(new BasicDBObject("cd", dateFormat.parse("2012-06-12T00:00:00Z")));

    // create and execute the query
    final Date to = dateFormat.parse("2013-06-30T09:12:29Z");
    final Date from = dateFormat.parse("2013-06-11T09:12:29Z");

    Query query = new Query();
    query.addCriteria(Criteria.where("cd").gte(from).lte(to));

    // check it returned what we expected
    List<MyObject> basicDBObjects = mongoTemplate.find(query, MyObject.class);
    Assert.assertEquals(1, basicDBObjects.size());
    Assert.assertEquals(expectedDate, basicDBObjects.get(0).cd);
}

Notes:

  • This is TestNG not JUnit
  • I'm using SimpleDateFormat just to make testing of dates easier and (maybe) more readable

The main thing to note is:

query.addCriteria(Criteria.where("cd").gte(from).lte(to));

Before I reversed the order of the lte and gte the query was returning nothing.

Upvotes: 8

Related Questions