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.
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.
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}], })
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