Question

Using spring data mongo repository class, how do we declare a method to return the documents with few fields excluded? Spring data reference document shows 'include' fields mechanism but not exclude. Code from spring documentation:

public interface PersonRepository extends MongoRepository<Person, String>

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

}

I need a mechanism to specify the fields to be excluded? Is this supported for repository methods?

Was it helpful?

Solution

specify the fields value as 0. Ex:

public interface PersonRepository extends MongoRepository<Person, String>

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

}

This will not fetch firstname property of the document and value will be null in returned java object.

OTHER TIPS

Add an empty filter criteria for findAll query:

public interface PersonRepository extends MongoRepository<Person, String> {
    @Query(value = "{}", fields = "{ 'firstname' : 0 }")
    List<Person> findAll(Sort sort);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top