Many-to-Many Relations in MongoDB
Introduction
Welcome to the next lesson of our "Schemas and Relations" course! Previously, we explored one-to-one and one-to-many relations in MongoDB. Now, we will dive into the realm of many-to-many relations in MongoDB, examining how to model these relationships using both embedded documents and references.
What are Many-to-Many Relations?
A many-to-many relation occurs when multiple entities of one type are associated with multiple entities of another type. For example, consider authors and books: an author can write multiple books, and a book can have multiple authors. This establishes a many-to-many relation between authors and books.
Similar to one-to-one and one-to-many relations, we can represent many-to-many relationships in MongoDB using two primary methods:
- Embedded Documents: The related data is included as an embedded array within the parent document.
- References: The
_idvalues of multiple documents are stored in an array within another document, creating references to them.
Representing Many-to-Many Relations Using Embedded Documents
Embedded documents in MongoDB allow you to store related data within a parent document, making it easy to retrieve all the information in a single query. This method is suitable when the "many" side of the relation has a manageable number of elements. However, it can lead to data duplication.
Here's an example representing authors and books using embedded documents:
In this code snippet:
- We insert multiple book documents into the
booksEmbeddedcollection usinginsertMany(). - Each book document contains a
title,authorsarray, andpublished_year. Theauthorsarray includes embedded documents representing each author.
This setup efficiently represents the many-to-many relationship between authors and books using embedded documents. Notice that we have data duplication for Neil Gaiman in the authors array of the respective books.
