Question

EDITED

I would like to find the children element when only the parent element is known. I can'f ding the equest (I am using mongodb) Here is the structure:

collection: parent2

parent1  
    id: idParent1   name : parentName1  //no ref to the children elements
parent2  
    id: idParent2   name : parentName2  //no ref to the children elements
parent3 
    id: idParent3   name : parentName3   //no ref to the children elements


collection: children

child1
    id: idChild1   refParent:   parent1
    id: idChild2   refParent:   parent2
    id: idChild3   refParent:   parent3
    id: idChild4   refParent:   parent3
    id: idChild5   refParent:   parent1

The request would be something like

 Query query = new Query();
 query.addCriteria(Criteria.where("child.refParent").is("parent1")); //not working 
 return mongoTemplate.find(query, Chidren.class);

The java classes I use to create the collection are:

public Parent{

  String id;

  String name; 

}



public Child {

   String id;

   String name;

   Parent parent;


}
Was it helpful?

Solution

Your java classes are not the same as the structure.

Based on the structure: the collection name "child" should not be part of the where criteria, use:

query.addCriteria(Criteria.where("refParent").is("parent1"));

Based on the Java code:

query.addCriteria(Criteria.where("parent.id").is("parent1"));

See the example in reference documentation for more details:

http://docs.spring.io/spring-data/data-mongodb/docs/current/reference/htmlsingle/#mongodb-getting-started.

But do you really store whole parent in each child? This is definitely not a correct way to model data in document database. What you should have is

public Child {

   String id;

   String name;

   String parentId;

}

or use DBRef, but only if you have very good reason.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top