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?

有帮助吗?

解决方案

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.

其他提示

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);
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top