title: How to cascade delete document in mongodb?
body: <p>I have user and photo documents in Mongodb. Each photo belongs to user and a photo maybe shared among users. Lets say user1 has p1,p2,p3 photos and user2 has p3,p4,p5 photos. If I delete user1 (manually using tools like Compass), p1 and p2 should also be deleted but not p3. How to achieve this and what kind of database structure I need to define?</p>
  
  <p>Currently if I delete user1, no photos are deleted and remain in databse which now makes the database corrupted from the point of view of the application using the database.</p>
  
  <p>Its Spring Boot app and User and Photo are declared as:</p>
  
  <pre><code>import lombok.Builder;
  import lombok.Data;
  import org.springframework.data.annotation.Id;
  import org.springframework.data.mongodb.core.mapping.DBRef;
  import org.springframework.data.mongodb.core.mapping.Document;
  @Document
  @Data
  @Builder
  public class User {
  
      @Id
      private String id;
  
  
      @DBRef
      private Set&lt;Photo&gt; photos;
  
  
      private String name;
  }
  
  @Document
  @Data
  @Builder
  public class Photo {
  
      @Id
      private String id;
  
  
      private String fileName;
  
  }
  </code></pre>