Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nosql many-to-many

What is the accepted pattern for handling many-to-many relationships in a document database design?

like image 346
detroitpro Avatar asked Jan 06 '11 06:01

detroitpro


People also ask

Which database is best for many-to-many relationship?

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.

Can MongoDB model many-to-many?

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.

Does NoSQL have relationships?

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.


1 Answers

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.

like image 82
Eric Bloch Avatar answered Oct 14 '22 07:10

Eric Bloch