0

I'm using SpringRepository to query mongo db. I have a students collection with documents like the following.

{
    "_id" : ObjectId("52f2139ee4b0384b7402c520"),
    "subjects": [
         {
             "subjectId" : "s001",
             "subjectName" : "maths"
         },
         {
             "subjectId" : "s002",
             "subjectName" : "science"
         },             
    ]
}

I'm going to query this collection using Spring Repository for a subject. I can get a student list with a particular subject like this

@Query("{ 'subjects.subjectName' : ?0 }")
List<Student> findBySubjectName(String subjectName);

But if I want subject only, how to return the a Subject object matching the subject name?

chk
  • 534
  • 3
  • 12
Susitha Ravinda Senarath
  • 1,648
  • 2
  • 27
  • 49

1 Answers1

0

This should work: (untested code...)

@Query(value="{ 'subjects.subjectName' : ?0 }", fields="{ 'subjects.$' : 1 }")
List<Student> findBySubjectName(String subjectName);

The basic syntax of projections with @Query can be found here, the projection syntax from this question.

Note that you will still obtain a Student object with null mapped to all fields that have not been fetched. If you don't want that, you will have to implement the query yourself (which is not hard) and return the required field of the fetched document in your method.

Community
  • 1
  • 1
chk
  • 534
  • 3
  • 12