2

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?

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

how then can you tell the difference between included field that has null value vs excluded field?
0

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.