面向文檔的數(shù)據(jù)
Schema 設(shè)計(jì)原則
在任何數(shù)據(jù)庫系統(tǒng)中建模數(shù)據(jù)時悬嗓,下面這些問題都需深思熟慮污呼。
- 數(shù)據(jù)的基本單元是什么?
RDBMS中有帶行列的數(shù)據(jù)表包竹,鍵值存儲中有指向不定類型值的鍵燕酷,MongoDB中數(shù)據(jù)的基本是BSON文檔。 - 如何查詢并更新數(shù)據(jù)周瞎?
RDBMS有即時查詢和聯(lián)結(jié)操作查詢苗缩,MongoDB也有即時查詢但不支持聯(lián)結(jié)操作,鍵值存儲只能根據(jù)單個鍵獲取值声诸。 - 應(yīng)用程序的訪問模式是什么酱讶?
除了理解數(shù)據(jù)的基本單元和數(shù)據(jù)庫的特性,還需明確應(yīng)用程序的需求彼乌。
在確定理想的數(shù)據(jù)模型前浴麻,必須問無數(shù)個與應(yīng)用程序有關(guān)的問題,讀寫比是多少囤攀?需要何種查詢?數(shù)據(jù)是如何更新的宫纬?能想到什么并發(fā)問題焚挠?數(shù)據(jù)的結(jié)構(gòu)化程度如何?
設(shè)計(jì)電商數(shù)據(jù)模型
電商站點(diǎn)通常要求有事務(wù)漓骚,而事務(wù)是RDBMS的主要特性蝌衔。
產(chǎn)品分類
> var doc={
slug:"gardening-tools",
ancestors:[
{name:"Home",slug:"home"},
{name:"Outdoors",slug:"outdoors"},
],
parent_id:ObjectId(),
name:"Gardening Tools",
description:"Gardening gadgets galore!"
};
> db.categories.insert(doc);
> db.categories.find();
{
"_id" : ObjectId("5a05b1e6f156220da1caf69e"),
"slug" : "gardening-tools",
"ancestors" : [
{
"name" : "Home",
"slug" : "home"
},
{
"name" : "Outdoors",
"slug" : "outdoors"
}
],
"parent_id" : ObjectId("5a05b1e6f156220da1caf69d"),
"name" : "Gardening Tools",
"description" : "Gardening gadgets galore!"
}
產(chǎn)品信息
存放基本產(chǎn)品信息,如產(chǎn)品名稱蝌蹂、SKU噩斟,其他表用來關(guān)聯(lián)送貨信息和價(jià)格歷史、屬性等等孤个。
# 創(chuàng)建數(shù)據(jù)庫
> use eshop;
#創(chuàng)建文檔
> var doc = {
slug:"wheel-barrow-9902", // URL短名稱剃允,需設(shè)置唯一性索引。
sku:"9902",
name:"Extra Large Wheel Barrow",
description:"Heavy duty wheel barrow...",
// 產(chǎn)品詳情
detail:{
weight:47,// 重量
weight_units:"lbs", // 計(jì)量單位
model_num:4039283402,//廠商型號代碼
manufacturer:"Acme",
color:"Green"http://顏色
},
total_reviews:4,
average_reviews:4.5,
// 當(dāng)前價(jià)格
pricing:{
retail:589700, //零售價(jià)
sale:489700//特價(jià)
},
//歷史價(jià)格
price_history:[
{retail:529700, sale:429700, start:new Date(2017,11,23), end:new Date(2017,12,21)},
{retail:529700, sale:529700, start:new Date(2017,10,21), end:new Date(2017,10,30)}
],
// 產(chǎn)品分類
category_ids:[
new ObjectId('5a05b1e6f156220da1caf69e')
],
main_cat_id: ObjectId(),
// 產(chǎn)品標(biāo)簽
tags:['tools', 'gardening', 'soil']
};
# 插入文檔
> db.products.insert(doc);
# 設(shè)置索引
> db.products.ensureIndex({slug:1},{unique:true})
> db.getCollection('products').ensureIndex({slug:1},{unqiue:true})
根據(jù)分類中的產(chǎn)品
> db.products.find({category_ids=>category['id']});
Error: Line 1: Unexpected token =>
查看指定產(chǎn)品的所有分類
db.categories.find({_id:{$in:product['category_ids']}});
ReferenceError: product is not defined :
@(shell):1:26