In MongoDB, a many-to-many relationship can be modeled in a couple of ways. Here are the most common approaches:
1. Using Reference Documents
In this approach, you create separate collections for each of the entities and store references (IDs) to related documents.
Example: Students and Courses
Students Collection:
{
"_id": ObjectId("student1"),
"name": "Alice",
"courseIds": [ObjectId("course1"), ObjectId("course2")]
}
{
"_id": ObjectId("student2"),
"name": "Bob",
"courseIds": [ObjectId("course2"), ObjectId("course3")]
}
Courses Collection:
{
"_id": ObjectId("course1"),
"title": "Math 101",
"studentIds": [ObjectId("student1")]
}
{
"_id": ObjectId("course2"),
"title": "History 201",
"studentIds": [ObjectId("student1"), ObjectId("student2")]
}
{
"_id": ObjectId("course3"),
"title": "Science 301",
"studentIds": [ObjectId("student2")]
}