MongoDB Schema設計場景案例說明

 

文:Johnson Wu

設計場景

MongoDB支援JSON格式儲存,因此單一Document可以直接存入多層格式的物件,但單一Document還是有最大16MB最大深度100的上限限制。

在這兩個條件下,我們以資料基數將基本的設計模式分為:

  • One-to-Few (少量)
  • One-to-Many (多量)
  • One-to-Squillions (海量)

One-to-Few

例如:將地址陣列的物件放在Person物件中,這種嵌入的設計方式適合用於當嵌入資訊是固定的且不會無限增長。

 

db.person.findOne()
{
    name: "Kate Monster",
    ssn: "123-456-7890",
    addresses : [
        { street: "123 Sesame St", city: "Anytown", cc: "USA" },
        { street: "123 Avenue Q", city: "New York", cc: "USA" }
    ]
}

 

One-to-Many

產品是由許多零件組成的,但零件可能會需要定期維護及更新,因此將零件的ObjectId放在產品(Products)Document中,產品(Products)及零件(Parts)的訂購系統,每個產品可能會有幾百個替換零件,但最高不會超過幾千個。

這是每個零件的Document:

 

> db.parts.findOne()
{
    _id : ObjectID("AAAA"),
    partno : "123-aff-456",
    name : "#4 grommet",
    qty: 94,
    cost: 0.94,
    price: 3.99
}
> db.products.findOne()
{
    name : "left-handed smoke shifter",
    manufacturer : "Acme Corp",
    catalog_number: 1234,
    parts : [                // array of references to Part documents
        ObjectID("AAAA"),    // reference to the #4 grommet above
        ObjectID("F17C"),    // reference to a different Part
        ObjectID("D2AA"),
        // etc
    ],
    ...
}

再透過程式方法查詢,來檢索特定零件:

// Fetch the Product document identified by this catalog number
> product = db.products.findOne({ catalog_number: 1234 });
// Fetch all the Parts that are linked to this Product
> product_parts = db.parts.find({ _id: { $in : product.parts } }).toArray();

 

One-to-Squillions

當蒐集主機日誌類型的資料時絕對產生超過上限大小16MB的限制,因此將主機ObjectId或Hostname存在每一個日誌中。

> db.hosts.findOne()
{
    _id : ObjectID("AAAB"),
    name : "goofy.example.com",
    ipaddr : "127.66.66.66"
}
> db.logmsg.findOne()
{
    time : ISODate("2014-03-28T09:42:41.382Z"),
    message : "cpu is on fire!",
    host: ObjectID("AAAB"),       // Reference to the Host document
		hostname: "goofy.example.com"
}

再利用程式方法查詢,來檢索特定主機的日誌

// find the parent "host" document
> host = db.hosts.findOne({ ipaddr: "127.66.66.66" });  // assumes unique index
// find the most recent 5000 log message documents linked to that host
> last_5k_msg = db.logmsg.find({ host: host._id }).sort({ time: -1 }).limit(5000).toArray()
// find by hostname
> last_5k_msg = db.logmsg.find({ hostname: host.name }).sort({ time: -1 }).toArray()

這種方法不需在主機Document中紀錄所有日誌的ObjectId,因日誌的數量是無上限的,很快就會超過Document最大16MB的限制。

專人協助

由偉康業務人員為您詳細說明偉康的解決方案,以及相關產業經驗。


聯絡我們

https://www.webcomm.com.tw/blog/485/elasticsearch-ml-anomaly-detection-1/

訂閱偉康科技洞察室部落格,掌握最新科技趨勢!

立即訂閱電子報

掌握最新科技趨勢!