Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cascade delete document in mongodb?

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?

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.

Its Spring Boot app and User and Photo are declared as:

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<Photo> photos;


    private String name;
}

@Document
@Data
@Builder
public class Photo {

    @Id
    private String id;


    private String fileName;

}
like image 973
ace Avatar asked Sep 03 '18 10:09

ace


2 Answers

As mentioned by m4gic and in the questions he linked (here and here), MongoDB doesn't support cascading deletes. In your situation you should probably create an array in the User object, and put the complete child documents into that array instead of keeping them in their own collection. That way they will be deleted together with the parent, because they are a part of it.

like image 131
Mindcraft Avatar answered Sep 19 '22 16:09

Mindcraft


MongoDB doesn't support for cascade delete as of now. As you are already storing the ref photos in the User model, you can get the photo ids from the reference list and delete the photos together. Or instead of storing the photos in the separate collection you can have the array of Photos embedded into the user object.

You can refer to this link as well: What is the recommended equivalent of cascaded delete in MongoDB for N:M relationships?

like image 41
Archit Sud Avatar answered Sep 19 '22 16:09

Archit Sud