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

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


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.


You can use

Query query = new Query();query.fields().include("path");


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