简体   繁体   English

在spring data mongodb存储库中的@Query注释中使用$或运算符

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

I am using spring-data-mongodb. 我正在使用spring-data-mongodb。

I want to use $or operator in my repository. 我想在我的存储库中使用$或operator。

This is my query: 这是我的查询:

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

How do use $or in @Query so as it can match either type or name and fetch me a document. 如何使用$或@Query,因为它可以匹配任何类型或名称,并获取文档。 Please help. 请帮忙。

Per MongoDB reference for $or , your Query should be 根据$或 MongoDB 参考 ,您的查询应该是

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

you'll need to give pass type and name params. 你需要给出传递类型和名称参数。

I found answer to my question, which also handles optional query parameter in it. 我找到了我的问题的答案,它也处理了可选的查询参数。

Query should be : 查询应该是:

@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);

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM