简体   繁体   English

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

[英]SpringData MongoDB Repositories Query on multiple fields in nested object

I'm having trouble with a query on a nested object with two parameters. 我在查询具有两个参数的嵌套对象时遇到了麻烦。

Here is my document : 这是我的文件:

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

Here is my nested object : 这是我的嵌套对象:

public class Stakeholder{
    String nationalId;
    String stakeholderRole;
}

I'm using mongoRepository to query this collection : 我正在使用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);

Basically, I want to find a contract with contractRef and a stakeholder with both nationalId and stakeholderRole matching. 基本上,我想找到一个带有contractRef的合同以及一个与nationalId和interestholderRole都匹配的利益相关者。

I tried a simplier query : 我尝试了一个更简单的查询:

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

But this can return a contract which has a stakeholder with the matching nationalId and wrong role, and another stakeholder with the wrong nationalId and good role for example, so that's not what I want. 但是,这可能会返回一个合同,该合同的利益相关者具有相匹配的nationalId和错误的角色,而另一个利益相关者具有错误的nationalId和良好的角色,例如,这不是我想要的。

You could try using $elemMatch 您可以尝试使用$ 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM