What is the accepted pattern for handling many-to-many relationships in a document database design?
Junction table. When you need to establish a many-to-many relationship between two or more tables, the simplest way is to use a Junction Table. A Junction table in a database, also referred to as a Bridge table or Associative Table, bridges the tables together by referencing the primary keys of each data table.
A Many-to-Many relationship (N:M) As there is no single command to implement a many-to-many relationship in a relational database, it is more difficult than a one-to-many relationship. The same is true when using mongoDB to implement them. In fact, you can't use a command to create any type of relationship in MongoDB.
NoSQL databases can store relationship data — they just store it differently than relational databases do. In fact, when compared with relational databases, many find modeling relationship data in NoSQL databases to be easier than in relational databases, because related data doesn't have to be split between tables.
How you want to model the many-to-many will depend on what kind of queries you want to ask, how you want to update the data, etc... Say we have foos related to bars in a many to many fashion.
You could model a foo as
{
'bars': ['bar1', 'bar2', 'bar3']
}
and model a bar as
{
'foos': ['foo_x', 'foo_y', 'foo_z']
}
Or you could model the graph or relations between foo and bar as individual documents themselves
{
from: 'foo1',
to: 'bar1'
}
{
from: 'foo1',
to: 'bar2'
}
{
from: 'foo2',
to: 'bar3
}
{
from 'foo3',
to: 'bar3'
}
There are plenty of other ways too. How you want to do it will depend on the questions you want to ask, the operations you want to support, what you want to be efficient, and the indexing available in the database.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With