限制 Spring 数据 Mongo 存储库

Provide limit on Spring Data Mongo repository

使用最新的Spring数据Mongo(撰写时为2.1.1),如何指定获取"custom"查询方法的第一条记录?这是一个例子:

@Query(value="{name: ?0, approval: {'$ne': null}}",
        sort="{'approval.approvedDate': -1}",
        fields = "{ _id: 1 }")
List<Item> getLatestApprovedIdByName(String name, Pageable pageable);

/**
 * Finds the id of the most recently approved document with the given name.
 */
default Item getLatestApprovedIdByName(String name) {
    return getLatestApprovedIdByName(name, PageRequest.of(0, 1)).stream().findFirst().orElse(null);
}

理想情况下,我可以只使用 String 参数来注释 getLatestApprvedIdByName。 org.springframework.data.mongodb.repository.Query 注释上似乎没有限制字段。这看起来很奇怪,因为除了 "findFirst" 之外,我可以模拟命名方法所做的一切。没有 Pageable,我得到 IncorrectResultSizeDataAccessException,返回一个 List 是不可接受的,因为我不想浪费时间返回一个任意大的结果,加上复杂的代码需要处理 0 的可能性或 1 项。

因为您的查询 return 有多个文档,所以无法直接将其 return 设为单个 Item

使用Stream

// Repository
@Query(value="{name: ?0, approval: {'$ne': null}}",
        sort="{'approval.approvedDate': -1}",
        fields = "{ _id: 1 }")
Stream<Item> getLatestApprovedIdByName(String name);

// Service
default Item getLatestApprovedIdByName(String name) {
    return getLatestApprovedIdByName(name).stream().findFirst().orElse(null);
}

由于 Stream 的工作方式,您只会获取第一个查询结果,而不是整个结果集。有关更多信息,请参阅 documentation.

使用 PagePageable

// Repository
@Query(value = "{name: ?0, approval: {'$ne': null}}", fields = "{ _id: 1 }")
Page<Item> getLatestApprovedIdByName(String name, Pageable pageable);

// Service
default Item getLatestApprovedIdByName(String name) {
    PageRequest request = new PageRequest(0, 1, new Sort(Sort.Direction.DESC, "approval.approvedDate"));
    return getLatestApprovedIdByName(name, request).getContent().get(0);
}

通过使用 PageRequest,您可以指定想要的结果数量以及排序顺序。基于 this answer.