如何在mongodb中级联删除文档? [英] How to cascade delete document in mongodb?

查看:113
本文介绍了如何在mongodb中级联删除文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Mongodb 中有用户和照片文档.每张照片都属于用户,一张照片可能会在用户之间共享.假设 user1 有 p1,p2,p3 照片,user2 有 p3,p4,p5 照片.如果我删除 user1(手动使用 Compass 之类的工具),p1 和 p2 也应该被删除,而不是 p3.这个怎么实现,需要定义什么样的数据库结构?

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?

目前,如果我删除 user1,则不会删除任何照片并保留在数据库中,这使得从使用数据库的应用程序的角度来看,数据库已损坏.

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.

它的 Spring Boot 应用和 User 和 Photo 声明为:

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;

}

推荐答案

正如 m4gic 所提到的和他链接的问题 (此处此处),MongoDB 不支持级联删除.在您的情况下,您可能应该在 User 对象中创建一个数组,并将完整的子文档放入该数组中,而不是将它们保存在自己的集合中.这样它们就会和父对象一起被删除,因为它们是它的一部分.

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.

这篇关于如何在mongodb中级联删除文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆