mahendra kawde
mahendra kawde

Reputation: 847

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

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.

Upvotes: 3

Views: 8337

Answers (3)

mahendra kawde
mahendra kawde

Reputation: 847

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

Upvotes: 4

Oliver Drotbohm
Oliver Drotbohm

Reputation: 83171

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

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

Upvotes: 2

ikumen
ikumen

Reputation: 11663

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.

Upvotes: 6

Related Questions