Home > Software engineering >  Spring MongoDB Criteria: How to check that the List exists and contains object with specific value?
Spring MongoDB Criteria: How to check that the List exists and contains object with specific value?

Time:05-19

How to check that the List<Object> exists and contains an object of class whose partnerRole field value is equal to "CREATOR" and companyId field value is equals to "123"?

Document class:

@Document
public class ApplicationDocument {
    List<PartnerDocument> partners = new ArrayList<>();
}

@Document
public class PartnerDocument {

  private PartnerRole partnerRole;
  private String companyId;
  ...

  public enum PartnerRole {
    UNKNOWN_ROLE,
    CREATOR,
    PARTICIPANT
  }
}

My method for generating a List of Criteria. But that won't work because I'm referring to partners as if it were a PartnerDocument object, but partners is actually a List<PartnerDocument>.

  public  List<Criteria> getCriteria(Partner.PartnerRole role, String companyId) {
    List<Criteria> criteriaList = new ArrayList<>();
    criteriaList.add(Criteria.where("partners").exists(true));
    criteriaList.add(
        Criteria.where("partners.partnerRole").in(role)
    );
    criteriaList.add(
        Criteria.where("partners.partnerRole").in(companyId)
    );
    return criteriaList;
  }

CodePudding user response:

There is a mistake in your second criteria.

Criteria.where("partners.partnerRole").in(companyId) 

You are checking companyId against partnerRole.

It should be

Criteria.where("partners.companyId").in(companyId)
  • Related