在 spring 数据 mongodb 存储库的 @Query 注释中使用 $or 运算符

Use $or operator in @Query annotation in spring data mongodb repository

我正在使用 spring-data-mongodb.

我想在我的存储库中使用 $or 运算符。

这是我的查询:

@Query("{'type':?0}")
List<Doc> findByType(String type, Pageable pageable);

如何在@Query 中使用 $or 以便它可以匹配类型或名称并为我获取文档。 请帮忙。

根据 MongoDB reference for $or,您的查询应该是

@Query("{'$or':[ {'type':?0}, {'name':?1} ]}")

您需要提供传递类型和名称参数。

您甚至不需要为此手动定义查询:

Page<Doc> findByTypeOrName(String type, String name, Pageable pageable);

我找到了问题的答案,其中还处理了可选的查询参数。

查询应该是:

@Query("{'type':?0,'$or':[{ $where: '?1 == null' },{'key':?1},{ $where: '?2 == null' },{'username':?2}]}")
    List<Doc> findByType(String type, String key, String username, Pageable pageable);