Search code examples
spring-bootspring-mvcmongodb-querymongorepository

findAll method Mongo Repository - exclude fields to build lighter objects


I am using Spring Boot. I want to implemented findAll(boolean collapsed) method on my service. I am using MongoRepository as dao, and I wanted to use findAll method. If this collapsed parameter is set to false, then I return dao.findAll(), but if collapsed is set to true, I wanted to exclude some heavy fields (like list). Can I exclude this fields with queries and using a constructor of my class which has less input parameters? I am new to querying with MongoRepository.

Thank you in advance


Solution

  • if using MongoRepository you can restrict the fields (see https://docs.spring.io/spring-data/mongodb/docs/1.3.3.RELEASE/reference/html/mongo.repositories.html)

    @Query(value="{ 'firstname' : ?0 }", fields="{ 'firstname' : 1, 'lastname' : 1}")
    List<Person> findByThePersonsFirstname(String firstname);
    

    If you want to return different fields based on the parameter you can define 2 different methods in the MongoRepository interface