title: MongoDB One-to-Many and Many-to-One relations
body: <p>I'm trying to optimize my MongoDB collections. This is the example:</p>
  
  <pre><code>@Document
  class Article {
      @Id
      private String id;
      @DBRef(lazy = true)
      @CascadeSave
      private List&lt;Comment&gt; comments;
      private String title;
      private String text;
  
      // constructors, getters and setters are ommited
  }
  
  @Document
  class Comment {
  
      @Id
      private String id;
      private String text;
      private String author;
  
      // constructors, getters and setters are ommited
  }
  </code></pre>
  
  <p>Look's quite simple. Get the article, then get all the comments for this article. But what if I already have article id, and just want to get all the comments for my article? Sure it's simple too. Every comment should have reference to the article it belongs to (for example article_id).</p>
  
  <p>My question is how can I do it automatically? How can I insert article_id to the comment while saving/updating etc? Or I should add field to Comment class and than first save article, then get article_id, then get comments, add article_id, save comments and add comments to the article comments collection? This has no sense for me. </p>
  
  <p>I'm using Java 10, with Spring Boot 2.0.5 including spring-data-mongodb and the reactive driver. I have also implemented @CascadeSave annotation for saving the comments while saving article.</p>
  
  <p>Thanks for your replies.</p>