问题
What is the accepted pattern for handling many-to-many relationships in a document database design?
回答1:
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.
回答2:
Assuming we are talking about cases where a relationship is really necessary rather than the ones which only exist because SQL handles relationships better than complex objects, the design is similar to the standard one for SQL - two one to many relationships.
The key difference is that you have multivalue fields, so instead of a third document/table recording single connections as a pair of ids, you have a list of ids in each document.
If you run into cases where that list gets too long you are likely looking at something that would be better handled by search indexing than a relationship.
来源:https://stackoverflow.com/questions/4612426/nosql-many-to-many