title: Spring Data mongodb date range query
body: <p>I am using spring data with mongodb to create an application. </p>
  
  <p>I have this object:</p>
  
  <pre><code>public class Room {
      private String name;
      private List&lt;Date&gt; occupied;
  }
  </code></pre>
  
  <p>I want using <code>mongodbTemplate</code> preferably to get the list of room that are not occupied for a date range.</p>
  
  <p>So for example if i have a start date 10/10/2014 and end date 15/10/2014 I want to get the list of rooms that do not have in the list occupied the dates 10,11,12,13,14,15 for October 2014.</p>
  
  <p>Does anyone have any idea on this?</p>
  
  <p>Update:</p>
  
  <p>I have found a way to do this by using this query:</p>
  
  <pre><code>query.addCriteria(Criteria.where("occupiedDates")
     .ne(from).andOperator(
         Criteria.where("occupiedDates").ne(to))
  );
  </code></pre>
  
  <p>the problem is that I can not dynamically add the andOperator. </p>
  
  <p>I would prefer inside the criteria to add a list of dates if possible.</p>
  
  <p>An example document is (only one record exists in mongo this one) :</p>
  
  <blockquote>
    <p>Room(bedcount=1, bedtype1=1, bedtype2=0, bedtype3=0, bedtype4=0,<br>
    filetype=null, noofrooms=0, occupancy=0, photo=null, rateid=1,<br>
    roomname=null, roomno=888, status=null,<br>
    roomTypeID=26060747427845848211948325568, occupiedDates=[Sun Aug 10<br>
    00:00:00 EEST 2014, Mon Aug 11 00:00:00 EEST 2014, Tue Aug 12 00:00:00<br>
    EEST 2014, Wed Aug 13 00:00:00 EEST 2014], attributes={})</p>
  </blockquote>
  
  <p>And this is the code of how the wyeru is built:</p>
  
  <pre><code>SimpleDateFormat dateFormat = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
  Date to = null;
  Date from = null;
  try {
      to = dateFormat.parse("12-08-2014 00:00:00");
      from = dateFormat.parse("10-08-2014 00:00:00");
  } catch (ParseException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
  }
  DBObject c1 = new BasicDBObject("occupied", null);
  DBObject c2 = BasicDBObjectBuilder.start()
      .push("occupied").push("$not")
      .push("$elemMatch").add("$gte", from).add("$lte", to).get();
  
  Criteria c = Criteria.where("$or").is(Arrays.asList(c1, c2));
  Query query = new Query().addCriteria(c);
  List&lt;Room&gt; rooms = mongoTemplate.find(query, Room.class);
  </code></pre>
  
  <p>This query is sent to mongodb</p>
  
  <pre><code>{ "$or" : [
    { "occupied" :  null } ,
    { "occupied" :
      { "$not" :
        { "$elemMatch" :
          { "$gte" : { "$date" : "2014-08-09T21:00:00.000Z"} ,
            "$lte" : { "$date" : "2014-08-11T21:00:00.000Z"}
          }
        }
      } 
    }
  ]}
  </code></pre>
  
  <p>from this we understand that the query should return nothing. but it returns me 1 row. </p>