这是相当简单的,我们需要做一个放松,匹配,然后分组:
db.so.aggregate( [
{ $unwind : '$attrib' },
{ $match: { 'attrib.k' : 'color' } },
{ $group: { _id: '$attrib.v', count: { '$sum': 1 } } }
] );
Unwind 将“attrib”数组分解为每个数组元素一个文档:
{
"result" : [
{
"_id" : ObjectId("51eeb9f2812db9ff4412f132"),
"attrib" : {
"k" : "color",
"v" : "red"
}
},
{
"_id" : ObjectId("51eeb9f2812db9ff4412f132"),
"attrib" : {
"k" : "shape",
"v" : "rectangle"
}
},
{
"_id" : ObjectId("51eeb9f2812db9ff4412f132"),
"attrib" : {
"k" : "color",
"v" : "blue"
}
},
{
"_id" : ObjectId("51eeb9f2812db9ff4412f132"),
"attrib" : {
"k" : "avail",
"v" : true
}
}
],
"ok" : 1
}
匹配然后删除所有非颜色项目:
{
"result" : [
{
"_id" : ObjectId("51eeb9f2812db9ff4412f132"),
"attrib" : {
"k" : "color",
"v" : "red"
}
},
{
"_id" : ObjectId("51eeb9f2812db9ff4412f132"),
"attrib" : {
"k" : "color",
"v" : "blue"
}
}
],
"ok" : 1
}
小组终于让它回来了:
{
"result" : [
{
"_id" : "blue",
"count" : 1
},
{
"_id" : "red",
"count" : 1
}
],
"ok" : 1
}
(以上所有输出仅来自您的单个示例文档)