我想转换以下查询:
{ "cd" : { "$lte" : ISODate("2013-06-30T09:12:29Z") , "$gte" : ISODate("2013-06-11T09:12:29Z")}}
与MongoTemplate和Query一起使用.
目前我正在做和接近:
Query query = new Query();
query.addCriteria(Criteria.where("cd").lte(request.getTo()).gte(request.getFrom()));
mongoTemplate.find(query,MyDesiredEntity.class)
但是当第一个返回大约15时,上面的查询没有返回结果(request.getTo和request.getFrom是java.util.Date).
有没有办法用org.springframework.data.mongodb.core.query.Query实现这一目标
解决方法:
我通过颠倒lte和gte调用来实现这一点.我写了一个测试来证明它有效:
@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);
}
笔记:
>这是TestNG而不是JUnit
>我正在使用SimpleDateFormat只是为了更简单地测试日期,并且(可能)更具可读性
需要注意的主要事项是:
query.addCriteria(Criteria.where("cd").gte(from).lte(to));