Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to represent a many-to-many or many-to-one relationship in MongoDB?

Tags:

mongodb

I'm learning about MongoDB and I have a question: How do you represent Many-to-Many or Many-to-One relationships? In a standard SQL DB it would be simple:

Parent Table has fields ID (primary key) and Name.
Child Table has fields ID (primary key) and Name
Parent-Child-Relationship Table has fields ID (primary key), ParentID and ChildID

insert into table Parent (ID, Name) values (1, "Bob");
insert into table Child (ID, Name) values (1, "Mahmoud");
insert into table Parent-Child-Relationship (ID, ParentID, ChildID) values (1,1,1);

But I have not figured out how to do this in MongoDB. I could do:

db.parent.save({name: "Bob", children: ["Mahmoud"]});

But then how would I be able to create another Parent (Say "Mary") for Mahmoud??

Am I missing something obvious? Please help. I'm a complete newby to NoSQL technology.

like image 291
Saqib Ali Avatar asked Nov 01 '22 15:11

Saqib Ali


2 Answers

The short answer is you don't.

The answer 10Gen would tell you is to use use a single document that is the parent, and subdocuments that represent the children.

However, don't do that, as subdocument queries in Mongo are limited and slower.

What everyone ends up doing is storing parent ID's on the children, and doing multiple queries/joins in the application level.

like image 51
Jonathan Holland Avatar answered Nov 09 '22 18:11

Jonathan Holland


Nothing stops you from creating another parent like below:

db.parent.save({name: "Jane", children: ["Mahmoud"]})

but I would say you are missing the point. Splitting data in row-like manner in document-oriented database is usually bad idea. Everything depends on application logic but if you want to reflect family data you can try for example structure like that:

db.family.insert({mother: {name: "Jane", age: 27}, father: {name: "Bob", age: 29}, children: [{name: "Mahmoud", age: 2}], })
like image 45
zero323 Avatar answered Nov 09 '22 17:11

zero323