java - mongo jpa 查询之间

标签 java spring mongodb jpa

我正在使用 spring jpa 与 mongo 数据库集成。我有一个带有 Instance 字段的简单 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
}

我也尝试过更改查询方法,如下

findByInstantGreaterThanEqualAndInstantLessThanEqual(Instant start, Instant end, Pageable pageable);

当我用这种方法运行测试时,我得到

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}}'.

有人遇到过这样的问题吗?

最佳答案

Between 查询方法工作正常。我不知道它是排他的,所以因为我只有一个包含两个元素的测试用例(分别是 startend Instant)查询在这些之间(不包括)查找并找到 0 个元素。

当我在 startend 中间添加另一个带有 Instant 的元素时,我预期是 3,但它返回了 1。

为了使查询具有包容性,我将其注释如下

@org.springframework.data.mongodb.repository.Query("{ instant: {$gte: ?0, $lte: ?1}}")

其中 ?0?1 分别对应于 startend 参数。

希望这可以帮助其他人。

关于java - mongo jpa 查询之间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58388706/

相关文章:

java - JComboBox 确定项目是否在下拉列表中可见

java - 属性 'profile' 不允许出现在元素 'beans:bean' 中

eclipse - Spring hello world 示例错误

mongodb - 将mongodb迁移到redis

python - 如何将在 Python 中创建的 bool 值传递给 MongoDB?

java - 名称升序 @FixMethodOrder 不适用于 Junit 测试

java - Mockito:使用 List<String> 作为参数

java - 为什么在 Spring 中使用 OncePerRequestFilter?

java - 元素 "mvc"的前缀 "mvc:resources"未绑定(bind)

ruby-on-rails - Mongoid错误 "undefined method `删除':format:Symbol"