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

8.1k Views Asked by At

I am using spring-data-mongodb.

I want to use $or operator in my repository.

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. Please help.

3

There are 3 best solutions below

1
On BEST ANSWER

Per MongoDB reference for $or, your Query should be

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

you'll need to give pass type and name params.

0
On

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);
0
On

You don't even need a manually defined query for that:

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