【发布时间】:2015-04-23 06:39:01
【问题描述】:
我有一个看起来像这样的产品集合:
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
}
]
}
]
我正在使用 distinct、aggregate 和 mapReduce 进行测试。但达不到需要的结果。谁能告诉我好方法吗?
更新:
使用聚合,这给了我产品具有的不同方面类别,但不是值,也不是不同值的计数:
db.products.aggregate([
{$match:{'content.facets.type':'category'}},
{$group:{ _id: '$content.facets.type'} }
]).pretty();
【问题讨论】:
-
向我们展示您使用 distinct、aggregated 和 mapReduce 进行的测试。
标签: mongodb