0

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 .

ashutosh
  • 81
  • 1
  • 1
  • 9
  • Performance involves too many variables so it will depends on what is a good performance for you, but if you need to reduce the number of times that the application reads the database you can use Caching https://spring.io/guides/gs/caching/. – Daniel C. Sep 18 '17 at 02:08
  • well my requirement is like this in some pages i only need one field in some case i need multiple fields if i consider the obvious when i need multiple fields i should get whole object and when i need single field i should get single one but i want to know is there benefit in that or did database performance work on no of query i do on it and not on the size of response it return – ashutosh Sep 19 '17 at 17:31

2 Answers2

1

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);
}
Marco
  • 741
  • 3
  • 18
0

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 .

ashutosh
  • 81
  • 1
  • 1
  • 9