简体   繁体   中英

How to represent a many-to-many or many-to-one relationship in 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM