javaspringmongodbmongorepository

Is there way to add default query to mongo repository?


Say, we have a class named person

public class Person{ 
   private String name;
   private boolean active; 
}

When I call personRepository.findByName("John Doe") the result should be the objects with the name John Doe and active is True. Meanwhile, when personRepository.findByNameAndActive("John Doe", false), it should return the result of all the objects with John Doe and active = false

Is there any way to do this ?


Solution

  • Unfortunately, default MongoRepository methods do not support OR or AND clauses.

    Supported keywords for query methods

    But you can use a @Query annotation to define what should be done by this method:

    @Query("{ 'name' : ?0, 'active' : true }")
    Person findByName(String name);
    
    @Query("{ 'name' : ?0, 'active' : ?1 }")
    Person findByNameAndActive(String name, boolean active);