简体   繁体   English

如何在MongoDB中表示多对多或多对一关系?

[英]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? 我正在学习MongoDB,我有一个问题:你如何代表多对多或多对一的关系? In a standard SQL DB it would be simple: 在标准的SQL DB中,它很简单:

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. 但我还没想出如何在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?? 但那我怎么能为Mahmoud创造另一个父母(说“玛丽”)?

Am I missing something obvious? 我错过了一些明显的东西吗 Please help. 请帮忙。 I'm a complete newby to NoSQL technology. 我是NoSQL技术的完全新手。

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. 10Gen会告诉你的答案是使用一个父文件和表示子文件的子文档。

However, don't do that, as subdocument queries in Mongo are limited and slower. 但是,请不要这样做,因为Mongo中的子文档查询是有限且较慢的。

What everyone ends up doing is storing parent ID's on the children, and doing multiple queries/joins in the application level. 每个人最终做的是将父ID存储在子节点上,并在应用程序级别中执行多个查询/连接。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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