title: MongoDB Nested objects with own Repository interface
body: <p>I am using Spring Data MongoDB to load and save some simple domain classes. As a simple example lets say I have Factory and Product</p>
  
  <pre><code>@Document
  public class Factory {
      @Id String id;
      String name;
      List&lt;Product&gt; products;
  }
  
  @Document
  public class Product {
      @Id String id;
      String name;
      Date productionDate;
  }
  </code></pre>
  
  <p>Ok, simple enough I can now create a <code>FactoryRepository</code>:</p>
  
  <pre><code>public interface FactoryQueryRepository extends MongoRepository&lt;Factory, String&gt; {}
  </code></pre>
  
  <p>This repository already has basic CRUD functionality to store and load Factories together with nested products. Now lets say I want to only retrieve a set of products for a given factory.</p>
  
  <p>I now have two questions:</p>
  
  <p><strong>A)</strong> Can I somehow return <strong>a list of products</strong> instead of a <strong>list of factories</strong> in the FactoryQueryRepository like so:</p>
  
  <pre><code>@Query(value = "???")
  public List&lt;Product&gt; findProductByFactoryName(String name);
  </code></pre>
  
  <p><strong>B)</strong> Lets say my factory does not only have products but also employees, customers, suppliers, you name it ... Now if need to define a few special query methods for each of these nested collections then I soon end-up with a very big <code>FactoryQueryRepository</code> interface. So it would actually be more appropriate to create a new <code>...QueryRepositoy</code> for Product, Employee, Customer and so on. But when I try to do this, it seems it only works if I first save a stand alone Product object that is not nested inside a Factory. Is there a way that I can (similar to question A) define a <code>ProductQueryRepository</code> interface and use it to retrieve all Products that are nested inside a Factory by specifying some filter criteria of the Factory, something like this:</p>
  
  <pre><code>public interface ProductQueryRepository extends MongoRepository&lt;Product, String&gt; {
      @Query(/* select products from factory where name = '?0' */)
      public List&lt;Product&gt; findProductsByFactoryName(String name);
  }
  </code></pre>
  
  <p>Shoud I in this case rather make use of the <code>@DBRef</code> than to use nested objects?</p>