【问题标题】:Using $slice in Spring MongoDB Repository with @Query在 Spring MongoDB 存储库中使用 $slice 和 @Query
【发布时间】:2018-08-25 18:15:13
【问题描述】:

我正在将 Spring Boot 与 MongoDB 一起使用。在这个项目中,我有域类 ControlVariable,它有一个名为 ControlVarEntries 的数组属性。在我自己的 findAll 方法中检索所有 controlVarEntries 时,我一直在尝试使用运算符 $slice 仅获取最后五个 controlVarEntries。在我的 Mongo 客户端中尝试此查询时有效:

db.getCollection('controlVariable').find( {}, { controlVarEntries: { $slice: -5 } } )

但是,我在我的 Spring Boot 项目中使用 @Query 注释尝试了类似的方法,但我无法检索到相同的结果。例如,这会返回所有条目:

@Repository
public interface ControlVariableRepository extends MongoRepository<ControlVariable, String> {

    @Query("{ controlVarEntries: { $slice: ?0 } }")
    Page<ControlVariable> findAllLimitedNumberOfEntriesQuery(Pageable pageable, Integer numberOfEntries);

}

我想知道我的查询是错误的还是我没有使用正确的语法。

谢谢!

【问题讨论】:

  • 我相信你应该使用$slice: ?1
  • 不幸的是,它也不起作用。我还应该说我尝试过不使用任何参数:@Query("{}, { controlVarEntries: { $slice: 5 } }") 但它也是错误的。

标签: spring mongodb spring-boot jhipster


【解决方案1】:

您必须在@Query 注释中识别投影文档。

试试

@Query(value="{}", fields = "{'controlVarEntries': { '$slice': ?0 } }")
Page<ControlVariable> findAllLimitedNumberOfEntriesQuery(Pageable pageable, Integer numberOfEntries);

【讨论】:

    猜你喜欢
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-06
    • 2020-05-14
    • 2022-06-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多