Spring Data MongoDB - Query Methods



Since MongoDBRepository works on top of CrudRepository, so we have access to all the query methods as well as custom query methods. As per business requirements, we can add some custom query methods to our customer repository −

import java.util.List;
import java.util.Optional;
import org.springframework.data.mongodb.repository.MongoRepository;
import com.tutorialspoint.document.Customer;
public interface CustomerRepository extends MongoRepository<Customer, Long>{
   Optional<Customer> findByEmail(String email);
   List<Customer> findBySalaryGreaterThanEqual(double salary);
   List<Customer> findBysalaryBetween(double from, double to);
}

We have added three query methods, which helps in finding the customers based on email and salary. Lets test these query methods by adding some code to CommandLineRunner.

@Bean
CommandLineRunner commandLineRunner(CustomerRepository customerReposito
ry) {
   return new CommandLineRunner() {
      @Override
      public void run(String... args) throws Exception {
         // Fetch by email
         System.out.println(customerRepository.findByEmail("john@yah
         oo.co"));
         // fetch whose salary is =>20000
         System.out.println(customerRepository.findBySalaryGreaterTh
         anEqual(20000));
         // fetch whose salary is in between 1000 to 12000
         System.out.println(customerRepository.findBysalaryBetween(1
         000, 12000));
      }
   };
}

In the above code, we are trying to fetch a customer by email and salary, it will print the result as follows −

Optional[Customer [id=1, name=Johnson, email=john@yahoo.co, salary=10000.0]
]
[Customer [id=2, name=Kallis, email=kallis@yahoo.co, salary=20000.0]]
[Customer [id=1, name=Johnson, email=john@yahoo.co, salary=10000.0]]
Advertisements