title: How can I query to find mongo entities whose list of sub-entities contain a field matching a string?
body: <p>I have a collection of entities that look like this:</p>
  
  <pre><code>public class ClientEntity {
  
      @Id
      private String id;
      @Indexed(unique = true)
      private String clientId;
      private String name;
  
      @DBRef
      private List&lt;ClientMachineEntity&gt; machines;
  
      ...
  }
  </code></pre>
  
  <p>...where ClientMachineEntity looks like:</p>
  
  <pre><code>public class ClientMachineEntity {
  
      @Id
      private String id;
      @Indexed(unique = true)
      private String clientMachineId;
      private String hostName;
  
      ...
  }
  </code></pre>
  
  <p>I have a working search that finds ClientEntities by matching against "clientId" and "name":</p>
  
  <pre><code>public List&lt;ClientEntity&gt; searchByIdAndName(String id, String name) {
  
      Criteria idCriteria = Criteria.where("clientId").regex(id, "i");
      Criteria nameCriteria = Criteria.where("name").regex(name, "i");
      Query query = new Query(new Criteria().orOperator(idCriteria, nameCriteria));
      ...
  }
  </code></pre>
  
  <p>So my question is, how can I expand this search so that it also matches against "clientMachineId" in the list of sub-entities?  I tried adding the following criteria:</p>
  
  <pre><code>Criteria machineCriteria = Criteria.where("machines.clientMachineId").regex(id, "i");
  </code></pre>
  
  <p>...but that doesn't work, presumably because machines is a LIST of entities, not just a single sub-entity.</p>
  
  <p>UPDATE: It seems like what I'm looking for is the .elemMatch() functionality, but when I try that:</p>
  
  <pre><code>Criteria machineCriteria = Criteria.where("machines").elemMatch(Criteria.where("clientMachineId").regex(id, "i"));
  </code></pre>
  
  <p>...I get the following error:</p>
  
  <pre><code>org.springframework.data.mapping.model.MappingException: No mapping metadata found for class com.mongodb.BasicDBObject
  </code></pre>