Spring Data MongoDB两个日期之间的日期

sic*_*ics 8 spring mongodb spring-data-mongodb

我正在使用Spring Data for MongoDB并获得以下类

class A {
    List<B> b;
}

class B {
    Date startDate;
    Date endDate;
}
Run Code Online (Sandbox Code Playgroud)

当我保存一个A的对象时,它就像持久化一样

{
    "_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")
          }
    ]
}
Run Code Online (Sandbox Code Playgroud)

现在我想在db中查询匹配b中条目的文档,其中给定日期在startDate和endDate之间.

Query query = new Query(Criteria.where("b").elemMatch(
    Criteria.where("startDate").gte(date)
    .and("endDate").lte(date)
);
Run Code Online (Sandbox Code Playgroud)

这导致以下mongo查询:

{
   "b": {
       "$elemMatch": { 
           "startDate" : { "$gte" : { "$date" : "2009-11-03T23:00:00.000Z"}}, 
           "endDate" : { "$lte" : { "$date" : "2009-11-03T23:00:00.000Z"}}
       }
   }
}
Run Code Online (Sandbox Code Playgroud)

但不返回任何结果文件.有谁知道我做错了什么?我不明白......

非常感谢你提前!!

Joh*_*yHK 11

如果你想找到的文档,其中date是间startDateendDate一个的b数组元素,那么你需要扭转你gtelte来电:

Query query = new Query(Criteria.where("b").elemMatch(
    Criteria.where("startDate").lte(date)
    .and("endDate").gte(date)
);
Run Code Online (Sandbox Code Playgroud)