Problem: I cannot find a document with a date greater than or date less than a given date. Spring Mongodb query's always return the same metric (Seemingly ignoring my sort order).
I have the following entity:
And the following method in my service used to search for a particular metric less than a particular date:Code:public class Metric { @NotNull private String name; @NotNull private double x; @NotNull private double y; @NotNull private double sd; @NotNull private double el; @Temporal(TemporalType.TIMESTAMP) @DateTimeFormat(iso=ISO.DATE_TIME) private Date date; }
I need the CLOSEST, which I thought sorting would handle. In PHP I used "TOP 1" after sorting based on date and it worked fine.Code:public Metric findByNameAndDateLessThan(String name, Date date){ Query q = query(where("name").is(name).and("date").lt(date)); q.sort().on("date", Order.DESCENDING); return mongoTemplate.findOne(q, Metric.class, "metric"); }
I wrote a test as follows:
The RESULT is always the earliest metric, even though I am sorting. It seems Spring Mongo is returning all the results and ignoring the sort order.Code:@Test public void testFindByNameAndDateLessThan(){ Metric m1 = mdod.getRandomMetric(); m1.setName("FindByNameAndLessThan"); m1.setDate(new Date(20000)); mr.save(m1); Metric m2 = mdod.getRandomMetric(); m2.setName("FindByNameAndLessThan"); m2.setDate(new Date(22000)); mr.save(m2); Metric result = ms.findByNameAndDateLessThan(m1.getName(), new Date(22100)); Assert.notNull(result, "Result must not be null. Did not find the latest metric"); Assert.isTrue(m2.getDate().compareTo(result.getDate()) == 0, "Result Metric is incorrect. Found date '" + result.getDate().toGMTString() +"' instead"); mr.delete(m1); mr.delete(m2); }
Is there something wrong with my timestamp? Or the format? I thought IDO Date was correct, but when Spring Roo starts it tells me "It is recommended to use @DateTimeFormat(style="M-") on java.util.Date.joinDate to use automatic date conversion in Spring MVC"
Thoughts? I don't want this to be show stopper and am on a tight deadline. Thank you.


Reply With Quote