Sobes.tech
Senior

How to implement a many-to-many relationship in a relational and document-oriented database?

sobes.tech AI

Answer from AI

In relational databases, a many-to-many relationship is implemented through an intermediate table (join table), which contains foreign keys to both related tables. For example, if there are tables Students and Courses, then a StudentCourses table is created with fields student_id and course_id.

CREATE TABLE Students (id INT PRIMARY KEY, name VARCHAR(100));
CREATE TABLE Courses (id INT PRIMARY KEY, title VARCHAR(100));
CREATE TABLE StudentCourses (
  student_id INT,
  course_id INT,
  PRIMARY KEY (student_id, course_id),
  FOREIGN KEY (student_id) REFERENCES Students(id),
  FOREIGN KEY (course_id) REFERENCES Courses(id)
);

In document-oriented databases (e.g., MongoDB), a many-to-many relationship can be implemented in two ways:

  1. Embedding arrays of related document identifiers in both collections (references).
  2. Creating a separate linking collection where each document contains references to both related entities.

Example with references:

// Student document
{
  "_id": "student1",
  "name": "Ivan",
  "course_ids": ["course1", "course2"]
}

// Course document
{
  "_id": "course1",
  "title": "Mathematics",
  "student_ids": ["student1", "student3"]
}

The choice of approach depends on data integrity requirements, update frequency, and data volume.