我正在使用MongoDB,我想要獲取數據以顯示多次使用Type和Subtype的菜單,如果我訪問一個子類型,系統將顯示子類型的產品。MongoDB中的最佳解決方案體系結構
示例1對我來說比較好,因爲我只是每種類型都有一個集合,但如果我不訪問任何子類型,我也會加載所有產品。好吧,我知道,我可以使用投影,但有可能使用帶有查詢的投影嗎?我可以投影一個子類型的產品嗎?所以也許例子2在這種情況下是正確的方式,但我有兩個集合和更多的關係。
您認爲最好的解決方案是什麼?
實施例1
集合類型:
{
"_id" : ObjectId("53fae88aafb3dc3494e03225"),
"name" : "TypeProduct",
"subtypes" : [
{
"name" : "Subtype1",
"products" : [
{
"$ref" : "products",
"$id" : ObjectId("53fee4fcafb358a62d7684c3"),
"sku" : "0001",
"picture" : "http...jpg"
},
{
"$ref" : "products",
"$id" : ObjectId("53fee656afb358a62d7684c4"),
"sku" : "0002",
"picture" : "http...jpg"
}
]
},
{
"name" : "Subtype2",
"products" : [
{
"$ref" : "products",
"$id" : ObjectId("53fee4fcafb358a62d7684c3"),
"sku" : "0001",
"picture" : "http...jpg"
},
{
"$ref" : "products",
"$id" : ObjectId("53fee656afb358a62d7684c4"),
"sku" : "0003",
"picture" : "http...jpg"
}
]
}
]
}
實施例2
集合類型
{
"_id" : ObjectId("53fae88aafb3dc3494e03225"),
"name" : "TypeProduct",
"subtypes" : [
{
"$ref" : "subtypes",
"$id" : ObjectId("53fee4fcafb358a62d7684c3"),
"name" : "Subtype1"
},
{
"$ref" : "subtypes",
"$id" : ObjectId("53fee4fcafb358a62d7684c3"),
"name" : "Subtype2"
}
]
}
收集亞型
{
"_id" : ObjectId("53fee4fcafb358a62d7684c3"),
"name" : "Subtype1",
"products" : [
{
"$ref" : "products",
"$id" : ObjectId("53fee4fcafb358a62d7684c3"),
"sku" : "0001",
"picture" : "http...jpg"
},
{
"$ref" : "products",
"$id" : ObjectId("53fee656afb358a62d7684c4"),
"sku" : "0002",
"picture" : "http...jpg"
}
]
}
以'$'爲前綴的字段是不允許的,因爲它是MongoDB中用於其他目的的保留字符。 –
是的,它是由Morphia生成的代碼,不是我的。 – user2443747