Watch keynotes and sessions from MongoDB.live, our virtual developer conference.

Foreign key constriant

Is there any way restrict document delete in mongodb if it is being as refrence to any other docuement(s) (something like foreign key constraint in mysql) or is there any other work around for this functionality.

Hi @sudeep_gujju,

As of current version (v4.2), there is no built-in feature within the database to restrict deletion of a “parent” document (equivalent to RESTRICT referential action on MySQL).

Depending on your use case, you could model the documents to embed the related documents. i.e. Model Embedded One-To-Many Relationships. I would also highly recommend Summary: Building With Patterns as a reference of modelling the document schema further.

Alternatively, you could write an application logic before any document alteration on the collection. i.e. check whether the document is referenced on another collection before performing the delete operation. etc.

Regards,
Wan.

1 Like