How to return only specific fields for a query in Spring Data MongoDB?

59,699

Solution 1

MongoDB only returns JSON documents for standard queries. What you'd like to see can be achieved by still returning a List<Foo>. The fields property in @Query will cause only the fields set to 1 being returned.

@Query(value="{ path : ?0}", fields="{ path : 0 }")
List<Foo> findByPath(String path);

We usually recommend introducing a dedicted DTO for that so that you prevent the partially filled Foo instance from being handed to save(…) in turn.

Another option is using the aggreation framework but that's more involved.

Solution 2

You can use

Query query = new Query();

query.fields().include("path");

Solution 3

You can use

public interface PersonRepository extends MongoRepository<Person, String>

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

}

More information in spring data documentation

Solution 4

You can use below query to get specific fields.

@Query(fields="{path : 1}")
Foo findPathByPath(String path);

Records present in DB

{
    "name" : "name2",
    "path" : "path2"
},
{
    "name" : "name3",
    "path" : "path3"
}

Below query will return Foo object if path=Path3

{
    "name": null,
    "path": "path3"
}

we need to specify required fields with fieldName:1 and if don't require then specify it with 0.

Share:
59,699

Related videos on Youtube

richersoon
Author by

richersoon

Updated on July 09, 2022

Comments

  • richersoon
    richersoon almost 2 years

    How can we select specific fields in Spring Data Mongo. I tried the following but I got cast exception from Foo to String.

    Using @Query

    @Query(value="{path : ?0}", fields="{path : 0}")
    String findPathByPath(String path);
    

    Non @Query

    String findPathByPath(String path);
    

    Here is the document model

    @Document(collection = "foo")
    public class Foo  {
    
      String name, path;
      …
    }
    
    • chrylis -cautiouslyoptimistic-
      chrylis -cautiouslyoptimistic- over 8 years
      What are you talking about? MongoDB doesn't have columns.
    • richersoon
      richersoon over 8 years
      I want to return only the specific field from my model. In sql it is equivalent of SELECT path FROM foo
    • PAA
      PAA about 5 years
      @Oliver Drotbohm - Is there any way if we can find out the distinct record out of the two?
  • VimalKumar
    VimalKumar about 7 years
    Oliver, Creating a DTO for every select query is not feasible as we run lot of queries to select sub set of data. Spring Data JPA returns List<Object[]> in cases where we dont want to map to DTO. Similalr to that, Is there any API to return a MAp of values instead of mapping to a DTO?
  • alvinmeimoun
    alvinmeimoun over 5 years
    If i want to get some fiels of all documents, i need to set value = "{}" , if i didn't set the value, it will check the name of the method. But i didn't check if in this case (not set the value) it will take care of the fields in the annotation
  • PAA
    PAA about 5 years
    @Nikhil Kumar K - Is there any way if we can findout the distinct records?
  • Nikhil Kumar K
    Nikhil Kumar K about 5 years
    @PAA Can you try findDistinctByThePersonsFirstname
  • PAA
    PAA almost 5 years
    @@Nikhil Kumar K - Method atleast expects one parameter in the method. I am simply looking find all FirstName
  • amir azizkhani
    amir azizkhani almost 5 years
    base on this part of your answer " fields="{ 'firstname' : 1, 'lastname' : 1} ", what mean ' 1 ' number? can you explain about that?