Announcement Announcement Module
Collapse
No announcement yet.
Querying date interval Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Querying date interval

    Hi All,

    I would like to query by date range from my Mongodb. I have a CRUDRepository extensions:

    @Repository
    public interface ValueRepository extends CrudRepository<ValueEvent, String>{
    @Query(value="{ 'deviceId' : ?0, 'date':{'$gte':?1} , 'date':{'$lte':?2}}")
    List<ValueEvent> findBetween(String deviceid, Date from, Date to);
    }

    the relevant part of entity is like that:

    @DateTimeFormat(iso=ISO.DATE_TIME)
    public Date getDate() {
    return this.date;
    }

    There are one objects for every day of year in database:
    ValueRepository vrepo = context.getBean(ValueRepository.class);
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.YEAR, 2012);
    for (int i=1; i<365;i++) {
    cal.set(Calendar.DAY_OF_YEAR, i);
    ValueEvent valueEvent = new ValueEvent("asdv", DeviceState.On, 42, "asdv value is 42");
    valueEvent.setDate(cal.getTime());
    vrepo.save(valueEvent);
    }

    When I tried to retrive records by:

    cal.set(Calendar.MONTH, Calendar.JULY);
    cal.set(Calendar.DAY_OF_MONTH, 18);

    Date from = cal.getTime();
    cal.set(Calendar.DAY_OF_MONTH, 30);
    Date to = cal.getTime();
    List<ValueEvent> bList = vrepo.findBetween("asdv", from, to);

    it founds all of element!

    When I tried it from mongoshell, it works well:

    db.valueEvent.find({'date':{'$gte':new Date(2012,6,1), $lte:new Date(2012,6,23)}})
    { "_id" : ObjectId("500cfa8e84ae1b97bf14d75c"), "_class" : "charris.example.domain.ValueEvent", "value" : 42, "deviceId" : "asdv", "state" : "On", "date" : ISODate("2012-07-01T07:17:34.391Z"), "message" : "asdv value is 42" }
    { "_id" : ObjectId("500cfa8e84ae1b97bf14d75d"), "_class" : "charris.example.domain.ValueEvent", "value" : 42, "deviceId" : "asdv", "state" : "On", "date" : ISODate("2012-07-02T07:17:34.391Z"), "message" : "asdv value is 42" }

    What mistake I do?

    I have a debian linux, Java 1.7.0_04, spring 3.2.0.M1, spring-data 1.2.1.RELEASE and mongo-java-driver-2.7.1

    thx,
    Zamek

  • #2
    I found the mistake!

    In the Repository there was wrong exception:
    @Query(value="{ 'deviceId' : ?0, 'date':{'$gte':?1} , 'date':{'$lte':?2}}")
    The correct expression is:
    @Query(value="{ 'deviceId' : ?0, 'date':{'$gte':?1 , '$lte':?2}}")

    Sorry, after I wrote this letter, I found the error.

    thx
    Zamek

    Comment

    Working...
    X