I would like to know how people design non-relational database projects. Take the course selection of students as an example. Each student can choose multiple courses. Each course can be selected by multiple students. How to design this many-to-many relationship? If I want to delete a course, how to ensure the consistency of the database?
MongoDB considers two basic modes: documents and sub-tables.
The document mode records a record in a document. Taking the course selection of a student as an example, it records all other courses under a student’s document. The sub-table model is like a relational database, in which students and courses are divided into tables, and then a table of the corresponding relationship (course selection) between students and courses is built.
The main advantage of documents is high reading efficiency, MongoDB does not
jointIf tables are divided, several queries must be made for each query involving several tables. The main disadvantage of the document is the inconvenience of maintenance. For example, if you modify the information of a course, you have to find all the student documents that contain the course and then modify them one by one. The size of another document is limited and data cannot be added indefinitely.
The advantages and disadvantages of sub-tables are opposite to those of documents.
In practice, the choice should be weighed. Data that is mainly read tends to choose the document mode. Data with high write/modify frequency can be divided into tables. In addition, for fields that may add data indefinitely, sub-table storage is usually considered.
Generally, the two are combined to record the information with higher reading frequency in the document, and other details are separately listed. In your example, students and courses build two tables. Each student’s document records the basic information (such as course code and name) of the course, and then the specific information of each course is stored in the curriculum schedule.
When you list the elective information of a student each time, you can list the codes and names of all elective courses in one query. When you need to view the detailed information of a specific course, you can make another query on the curriculum schedule. In this way, one query can be reduced compared with the complete sub-table, and the size of the document and the range to be modified when modifying the course information can be reduced compared with the complete document record.
If you want to delete a course, first delete the document of the course in the timetable, then find all the records containing the course in the student list and modify them. Flexible use of indexes and operators is not a problem.