MongoDB does not support FOREIGN KEY. It uses to avoid JOINS.
MongoDB does not support server-side foreign key relationships. But sometimes we need to tie. Therefore, MongoDB applications use one of two methods for linking documents:
Manual links , where you save the _id field of one document in another document as a link. Then your application can run a second query to return the related data. These links are simple and sufficient for most use cases.
DBRefs are links from one document to another, using the value of the firstid documents field, the name of the collection, and, if necessary, its database name. Including these names, DBRefs allow documents located in multiple collections to be more easily linked to documents from the same collection. This may not be so fast then, because the database must make additional queries to read objects, but it allows the appearance of a link to a foreign key. However, you will have to manually process your links. Just looking at your DBRef, you will see if it exists, the database will not go through all the documents to look for links and delete them if the link’s purpose no longer exists. But I think that deleting all the links after deleting the book will require a separate collection request, no more, so it's not that difficult.
See the documentation: Database Links for more information .
How can I solve this problem?
To be clear, MongoDB is not relational. There is no standard “normal form”. You must model your database that matches the stored data and the queries you intend to use. For ex -
student { _id: ObjectId(...), name: 'Jane', courses: [ { course: 'bio101', mark: 85 }, { course: 'chem101', mark: 89 } ] } course { _id: 'bio101', name: 'Biology 101', description: 'Introduction to biology' }
Try to solve this problem.
student { _id: ObjectId(...), name: 'Jane', courses: [ { name: 'Biology 101', mark: 85, id:bio101 }, ] }
source share