簡體   English   中英

如何在MongoDB中表示多對多或多對一關系?

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

我正在學習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技術的完全新手。

簡短的回答是你沒有。

10Gen會告訴你的答案是使用一個父文件和表示子文件的子文檔。

但是,請不要這樣做,因為Mongo中的子文檔查詢是有限且較慢的。

每個人最終做的是將父ID存儲在子節點上,並在應用程序級別中執行多個查詢/連接。

沒有什么可以阻止你創建另一個父母,如下所示:

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

但我會說你錯過了這一點。 在面向文檔的數據庫中以類似行的方式拆分數據通常是個壞主意。 一切都取決於應用程序邏輯,但如果你想反映家庭數據,你可以試試像這樣的結構:

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