MongoDB常用資料建模方式:1)文檔關係建模,2)樹結構建模
模型:
|-- 1、文檔關係建模
| |-- 1)內嵌文檔模型
| |-- 2)內嵌文檔模型
|-- 2、樹結構建模
|-- 1)父文檔引用
|-- 2)子文檔引用
|-- 3)祖先數組
|-- 4)物化路徑
|-- 5)嵌套集合
以下記錄了常用的建模及每一種模型的具體相關範例程式碼: 一、文檔關係建模:
1)內嵌文檔模型
{ _id: "joe", name: "Joe Bookreader", address: { street: "123 Fake Street", city: "Faketon", state: "MA", zip: "12345" }}
2)文檔引用模型
{ _id: "joe", name: "Joe Bookreader"}{ patron_id: "joe", street: "123 Fake Street", city: "Faketon", state: "MA", zip: "12345"}
二、樹結構建模
樹形業務結構圖:
(註:引用自mongodb中文官網圖)
1)父文檔引用
db.categories.insert( { _id: "MongoDB", parent: "Databases" } )db.categories.insert( { _id: "dbm", parent: "Databases" } )db.categories.insert( { _id: "Databases", parent: "Programming" } )db.categories.insert( { _id: "Languages", parent: "Programming" } )db.categories.insert( { _id: "Programming", parent: "Books" } )db.categories.insert( { _id: "Books", parent: null } )
2)子文檔引用
db.categories.insert( { _id: "MongoDB", children: [] } )db.categories.insert( { _id: "dbm", children: [] } )db.categories.insert( { _id: "Databases", children: [ "MongoDB", "dbm" ] } )db.categories.insert( { _id: "Languages", children: [] } )db.categories.insert( { _id: "Programming", children: [ "Databases", "Languages" ] } )db.categories.insert( { _id: "Books", children: [ "Programming" ] } )
3)祖先數組
db.categories.insert( { _id: "MongoDB", ancestors: [ "Books", "Programming", "Databases" ], parent: "Databases" } )db.categories.insert( { _id: "dbm", ancestors: [ "Books", "Programming", "Databases" ], parent: "Databases" } )db.categories.insert( { _id: "Databases", ancestors: [ "Books", "Programming" ], parent: "Programming" } )db.categories.insert( { _id: "Languages", ancestors: [ "Books", "Programming" ], parent: "Programming" } )db.categories.insert( { _id: "Programming", ancestors: [ "Books" ], parent: "Books" } )db.categories.insert( { _id: "Books", ancestors: [ ], parent: null } )
4)物化路徑
db.categories.insert( { _id: "Books", path: null } )db.categories.insert( { _id: "Programming", path: ",Books," } )db.categories.insert( { _id: "Databases", path: ",Books,Programming," } )db.categories.insert( { _id: "Languages", path: ",Books,Programming," } )db.categories.insert( { _id: "MongoDB", path: ",Books,Programming,Databases," } )db.categories.insert( { _id: "dbm", path: ",Books,Programming,Databases," } )
5)嵌套集合
db.categories.insert( { _id: "Books", parent: 0, left: 1, right: 12 } )db.categories.insert( { _id: "Programming", parent: "Books", left: 2, right: 11 } )db.categories.insert( { _id: "Languages", parent: "Programming", left: 3, right: 4 } )db.categories.insert( { _id: "Databases", parent: "Programming", left: 5, right: 10 } )db.categories.insert( { _id: "MongoDB", parent: "Databases", left: 6, right: 7 } )db.categories.insert( { _id: "dbm", parent: "Databases", left: 8, right: 9 } )