How can I query to find mongo entities whose list of sub-entities contain a field matching a string?

StackOverflow https://stackoverflow.com/questions/22411664

Pregunta

I have a collection of entities that look like this:

public class ClientEntity {

    @Id
    private String id;
    @Indexed(unique = true)
    private String clientId;
    private String name;

    @DBRef
    private List<ClientMachineEntity> machines;

    ...
}

...where ClientMachineEntity looks like:

public class ClientMachineEntity {

    @Id
    private String id;
    @Indexed(unique = true)
    private String clientMachineId;
    private String hostName;

    ...
}

I have a working search that finds ClientEntities by matching against "clientId" and "name":

public List<ClientEntity> 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));
    ...
}

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:

Criteria machineCriteria = Criteria.where("machines.clientMachineId").regex(id, "i");

...but that doesn't work, presumably because machines is a LIST of entities, not just a single sub-entity.

UPDATE: It seems like what I'm looking for is the .elemMatch() functionality, but when I try that:

Criteria machineCriteria = Criteria.where("machines").elemMatch(Criteria.where("clientMachineId").regex(id, "i"));

...I get the following error:

org.springframework.data.mapping.model.MappingException: No mapping metadata found for class com.mongodb.BasicDBObject
¿Fue útil?

Solución

You can't query by fields in subentities linked with DBRef. If ClientMachineEntity would be embedded in ClientMachine - then you could use dot notation or $elemMatch depending on needs.

In your particular example - couldn't field ClientMachineEntity.clientMachineId be saved as _id and used as a primary key? Then you could get the results you need - take a look at: How to query mongodb with DBRef

My suggestion for development with Spring Data MongoDB is - first learn how to (and if it's possible) do it in plain Javascript with MongoDB console, then learn how to do the same with Spring Data MongoDB.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top