5

我正在学习 MongoDB,我有一个问题:您如何表示多对多或多对一关系?在标准 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);

但我还没有弄清楚如何在 MongoDB 中做到这一点。我可以:

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

但是,我如何才能为 Mahmoud 创建另一个父母(说“玛丽”)?

我错过了一些明显的东西吗?请帮忙。我是 NoSQL 技术的新手。

4

2 回答 2

1

简短的回答是你没有。

10Gen 会告诉您的答案是使用作为父文档的单个文档和代表子文档的子文档。

但是,不要这样做,因为 Mongo 中的子文档查询有限且速度较慢。

每个人最终要做的是将父 ID 存储在子 ID 上,并在应用程序级别执行多个查询/连接。

于 2013-09-03T01:00:53.553 回答
1

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}], })
于 2013-09-03T01:03:47.880 回答