SpringData MongoDB存储库查询嵌套对象中的多个字段

时间:2019-01-22 14:11:03

标签: java spring mongodb spring-data spring-data-mongodb

我在查询带有两个参数的嵌套对象时遇到麻烦。

这是我的文档:

@Document(collection = "contracts")
public class Contract {
    @Id
    String _id;
    List<Stakeholder> stakeholders;
    Long contractRef;
}

这是我的嵌套对象:

public class Stakeholder{
    String nationalId;
    String stakeholderRole;
}

我正在使用mongoRepository查询此集合:

public interface ContractRepository extends PagingAndSortingRepository<Contract, String> {
@Query( value = "{'countryBranchCode' : ?0, 'contractRef' : ?1, 'stakeholders' : {'nationalId' : ?2, 'stakeholderRole' : ?3} }",
        fields = "{'stakeholders.$.':1}")
Contract findStakeholderByContractRefAndNationalIdAndStakeholderRole
        (String countryBranchCode, Long contractRef, String nationalId, String stakeholderRole);

基本上,我想找到一个带有contractRef的合同以及一个与nationalId和interestholderRole都匹配的利益相关者。

我尝试了一个更简单的查询:

@Query( value = "{'countryBranchCode' : ?0, 'contractRef' : ?1, 'stakeholders.nationalId' : ?2, 'stakeholders.stakeholderRole' : ?3  }",
        fields = "{'stakeholders.$.':1}")
Contract findStakeholderByContractRefAndNationalIdAndStakeholderRole
        (String countryBranchCode, Long contractRef, String nationalId, String stakeholderRole);

但是,这可能会返回一个合同,该合同的利益相关者具有相匹配的nationalId和错误的角色,而另一个利益相关者具有错误的nationalId和良好的角色,所以这不是我想要的。

1 个答案:

答案 0 :(得分:0)

您可以尝试使用$elemMatch

@Query( value = "{'countryBranchCode' : ?0,'contractRef':?1,'stakeholders':{'$elemMatch':{'nationalId':?2,'stakeholderRole':?3}}}",
fields = "{'stakeholders.$.':1}")
Contract findStakeholderByContractRefAndStakeholderRoleAndNationalId (String countryBranchCode, Long contractRef,String stakeholderRole, String nationalId);