Java 查询之间的mongo jpa

Java 查询之间的mongo jpa,java,spring,mongodb,jpa,Java,Spring,Mongodb,Jpa,我正在使用SpringJPA与mongo数据库集成。我有一个简单的mongo文档,其中有一个实例字段。在我的存储库中,我尝试了类似 findByInstantBetween(Instant start, Instant end, Pageable pageable); 我有一个简单的spring单元测试(使用spring runner和普通spring上下文运行),如下所示: import static org.assertj.core.api.Assertions.assertThat;

我正在使用SpringJPA与mongo数据库集成。我有一个简单的mongo文档,其中有一个
实例
字段。在我的存储库中,我尝试了类似

findByInstantBetween(Instant start, Instant end, Pageable pageable);
我有一个简单的spring单元测试(使用spring runner和普通spring上下文运行),如下所示:

import static org.assertj.core.api.Assertions.assertThat;

...


@Test
public void testSearchByInstantBetween() {
    // insert a document before the date range to test, should not be retrieved by query
    MyDocument doc = new MyDocument();
    doc.setInstant(Instant.now());
    doc= docRepository.insert(doc);

    // insert a document with the start instant, should be retrieved
    doc.setId(null);
    Instant start = Instant.now();
    doc.setInstant(start);
    doc = docRepository.insert(doc);

    // insert a document with the end instant, should be retrieved
    doc.setId(null);
    Instant end = Instant.now();
    doc.setInstant(end);
    doc = docRepository.insert(doc);

    // insert a document after the end instant, should not be retrieved
    doc.setId(null);
    doc.setInstant(Instant.now());
    doc = docRepository.insert(doc);

    // check that 4 documents have been inserted
    assertThat(docRepository.findAll()).hasSize(4);

    Pageable pageable = PageRequest.of(0, 5);

    // run between query, expected size is 2
    Page<MyDocument> docs = docRepository.findByInstantBetween(start, end, pageable);
    assertThat(docs.getContent()).hasSize(2); // <-- this fails with expected 2, found 0
}
当我用这个方法运行测试时,我得到

org.springframework.data.mongodb.InvalidMongoDbApiUsageException: Due to limitations of the com.mongodb.BasicDocument, you can't add a second 'instant' expression specified as 'instant: Document{{$lte=2019-10-15T06:28:43.508Z}}'. Criteria already contains 'instant : Document{{$gte=2019-10-15T06:28:43.505Z}}'.

有人遇到过这种问题吗?

中间的
查询方法工作正常。我不知道它是独占的,所以因为我只有一个包含两个元素的测试用例(
start
end
s),所以查询在这两个元素之间进行了查找(不包括),找到了0个元素

当我在代码的另一个元素中添加了<代码>即时< /代码> >开始< <代码> > <代码>结束>代码>时,我预期3,但返回1。 为了使查询具有包容性,我对其进行了如下注释

findByInstantGreaterThanEqualAndInstantLessThanEqual(Instant start, Instant end, Pageable pageable);
@org.springframework.data.mongodb.repository.Query("{ instant: {$gte: ?0, $lte: ?1}}")
其中,
?0
?1
分别对应于
开始
结束
参数


希望这能帮助其他人。

使用下面的示例查询查找大于或等于、小于或等于的内容

@Query("{instant : {$gte : ?0, $lte : ?1}}")
 findUsingQ(Instant start, Instant end, Pageable pageable);

第一个方法运行良好,即instantBetween非常好,这就是它返回零文档的原因。第二个方法签名是错误的,您不能将其用于您的需求。唯一的方法是使用@Query注释并编写查询。