Spring Data MongoDB Date between two Dates

为君一笑 提交于 2019-12-06 22:46:59

问题


i'm using Spring Data for MongoDB and got the following classes

class A {
    List<B> b;
}

class B {
    Date startDate;
    Date endDate;
}

when i save an object of A it gets persisted like

{
    "_id" : "DQDVDE000VFP8E39",
    "b" : [
          {
              "startDate" : ISODate("2009-10-05T22:00:00Z"),
              "endDate" : ISODate("2009-10-29T23:00:00Z")
          },
          {
              "startDate" : ISODate("2009-11-01T23:00:00Z"),
              "endDate" : ISODate("2009-12-30T23:00:00Z")
          }
    ]
}

Now i want to query the db for documents matching entries in b where a given date is between startDate and endDate.

Query query = new Query(Criteria.where("b").elemMatch(
    Criteria.where("startDate").gte(date)
    .and("endDate").lte(date)
);

Which results in the following mongo query:

{
   "b": {
       "$elemMatch": { 
           "startDate" : { "$gte" : { "$date" : "2009-11-03T23:00:00.000Z"}}, 
           "endDate" : { "$lte" : { "$date" : "2009-11-03T23:00:00.000Z"}}
       }
   }
}

but returns no resulting documents. Does anybody know what i'm doing wrong? I don't get it...

Thank you very much in advance!!


回答1:


If you want to find docs where date is between the startDate and endDate of a b array element then you need to reverse your gte and lte calls:

Query query = new Query(Criteria.where("b").elemMatch(
    Criteria.where("startDate").lte(date)
    .and("endDate").gte(date)
);



回答2:


{"created_at":{$gt:ISODate("2013-04-30T00:00:00Z"),$lt:ISODate("2013-04-30T23:59:59Z")}}


来源:https://stackoverflow.com/questions/12308756/spring-data-mongodb-date-between-two-dates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!