我有一个产品集合,看起来像: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你的测试。 –