我有一個產品集合,看起來像:MongoDB的選擇不同和計數
products = [
{
"ref": "1",
"facets": [
{
"type":"category",
"val":"kitchen"
},
{
"type":"category",
"val":"bedroom"
},
{
"type":"material",
"val":"wood"
}
]
},
{
"ref": "2",
"facets": [
{
"type":"category",
"val":"kitchen"
},
{
"type":"category",
"val":"livingroom"
},
{
"type":"material",
"val":"plastic"
}
]
}
]
我想選擇並計算不同類別和具有類別產品的數量(請注意,一個產品可以有多個類別)。類似的東西:
[
{
"category": "kitchen",
"numberOfProducts": 2
},
{
"category": "bedroom",
"numberOfProducts": 1
},
{
"category": "livingroom",
"numberOfProducts": 1
}
]
它會更好,如果我能得到相同的結果對每個不同的面型,這樣的事情:
[
{
"facetType": "category",
"distinctValues":
[
{
"val": "kitchen",
"numberOfProducts": 2
},
{
"val": "livingroom",
"numberOfProducts": 1
},
{
"val": "bedroom",
"numberOfProducts": 1
}
]
},
{
"facetType": "material",
"distinctValues":
[
{
"val": "wood",
"numberOfProducts": 1
},
{
"val": "plastic",
"numberOfProducts": 1
}
]
}
]
我做具有鮮明,聚集和MapReduce測試。但無法達到所需的結果。任何人都可以告訴我好方法嗎?
UPDATE:
與骨料,這給我的產品有不同的面類,而不是值也不值不同的計數:
db.products.aggregate([
{$match:{'content.facets.type':'category'}},
{$group:{ _id: '$content.facets.type'} }
]).pretty();
向我們展示具有鮮明,聚集和MapReduce你的測試。 –