我通过反转 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));
在我颠倒顺序之前lte
,gte
查询没有返回任何内容。