how should i get data from mongo db using spring mongo repository?

760 views Asked by At

i am using mongodb in my spring boot application and i am using mongo repository interface to get data from the database this is the way i am getting the data .

      School sch=repository.findOne("id");

this will give me the school object then i can get all the data from there but my question is will it affect my application's performance if i get the whole object everytime i need some data from that object even if i need some fields . if so what will be the method to do that i searched and i see that using Query annotiation i can limit the fields but even then it give whole object it put all the other fields null and data is only at fields which i specify . any guidence will be helpfull .

2

There are 2 answers

1
Marco On

You can use a projection interface to retrieve a subset of attributes. Spring Data Mongo DB

interface NamesOnly {
  String getName();
}

interface SchoolRepository extends Repository<School, UUID> {
  NamesOnly findOneById(String id);
}
0
ashutosh On

So after reading the documentation and reading other options this is the only solution i find where i can search the result using id and get only field i want in the result since i am only searching using the id so i have to overload the findbyId and since projection interface only change the return type i can not use that so here is what i did .

      @Query(value="{_id:?0}",fields="{?1:1,?2:1}")
List<School> findById(String schoolId, String fieldOne,String fieldTwo);

here ?0 is a place holder for schoolId and ?1 and ?2 are the placeholder for the fields name so now i can create these overloaded method which i can use to any no of fields the output is list of school since i am using id which is primary key so its just one school object list so i can just do get(0) to get my school object and it will have all the other fields as null this is the best i could find please share your thought to improve it i would love to hear other solutions .