There are many ways to avoid the null
values for fields that are not projected. In addition to the Interface-based Projections you can also try the following two ways. Consider a Pojo
class mapped to a collection's document:
public class Pojo {
private String fld1;
private Integer fld2;
private String fld3;
// constructor, get/set methods, toString(), ...
}
MongoRepository
methods which omit fld3
:
@Query(value="{'fld1' : ?0 }", fields="{ 'fld3' : 0 }")
List<Pojo> findByFld1(String fld1);
@Query(value="{'fld1' : ?0 }", fields="{ 'fld3' : 0 }")
List<Document> findByFld1Doc(String fld1);
@Query(value="{'fld1' : ?0 }", fields="{ 'fld3' : 0 }")
List<PojoProj> findByFld1Proj(String fld1);
Note the PojoProj
is another class with only the fields to be projected.
public class PojoProj {
private String fld1;
private Integer fld2;
// Add get methods for the two fields to be included and the toString()
}
Also, using org.bson.Document
class as result type allows omitting the null
valued fields in the output.
Run the following queries:
List<PojoProj> result1 = repository.findByFld1Proj("str-1");
List<Document> result2 = repository.findByFld1Doc("str-1");
These two queries will return objects with only the projected fields (omitting the fields with the null
values).