【问题标题】:How to omit fields while retrieving documents in spring-data-mongodb?如何在 spring-data-mongodb 中检索文档时省略字段?
【发布时间】:2020-07-06 05:48:08
【问题描述】:

我尝试使用以下 @Query 从包含 5 个字段的文档中仅检索 3 个字段。

@Query(value="{'organization':?0,'roleType':?1 }",fields="{'organization' : 0, 'roleType' :0}")
public List<Role> findByOrganizationAndRoleType(String organization, String roleType);

这给了我如下结果。

[
  {
    organization: null,
    firstName: "John",
    lastName: "Doe",
    nicNo: "5000",
    roleType: null
  }
]

是否可以省略字段,而不是像上面那样用“null”值显示它们。

【问题讨论】:

标签: mongodb spring-boot spring-data-mongodb


【解决方案1】:

您可以使用投影来限制结果中的数据。例如,如果您只需要显示用户的名字和姓氏,则提供如下界面并在您的存储库界面中使用它:

interface NamesOnly {

  String getFirstname();
  String getLastname();
} 


@Repository
interface RoleRepository extends Repository<Role, UUID> {

  @Query(value="{'organization':?0,'roleType':?1 }",fields="{'organization' : 0, 'roleType' :0}")
  public Collection<NamesOnly> findByOrganizationAndRoleType(String organization, String roleType);

}

我没有尝试执行上面的代码,但它提供了关于我想要传达的内容的一般概念。官方doc

【讨论】:

    【解决方案2】:

    有很多方法可以避免未投影字段的null 值。除了基于接口的投影之外,您还可以尝试以下两种方式。考虑一个映射到集合文档的Pojo 类:

    public class Pojo {
        private String fld1;
        private Integer fld2;
        private String fld3;
        // constructor, get/set methods, toString(), ...
    }
    

    MongoRepository 省略 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);
    

    注意PojoProj 是另一个类,只有要投影的字段。

    public class PojoProj {
        private String fld1;
        private Integer fld2;
        // Add get methods for the two fields to be included and the toString()
    }
    

    此外,使用 org.bson.Document 类作为结果类型允许在输出中省略 null 值字段。

    运行以下查询:

    List<PojoProj> result1 = repository.findByFld1Proj("str-1");
    List<Document> result2 = repository.findByFld1Doc("str-1");
    

    这两个查询将返回仅具有投影字段的对象(省略具有null 值的字段)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-02
      • 1970-01-01
      • 2019-07-23
      • 2019-06-18
      • 2018-07-13
      • 1970-01-01
      相关资源
      最近更新 更多