MongoDB 计数(如果存在)并按不同的数组值分组



我有一个看起来像这样的集合:

{
"_id" : 1,
"category" : [
{
"name": "category1"
},
{
"name": "category2"
}
],
"event": [
{
type: "house"
},
{
type: "mouse"
}
]
},
{
"_id" : 2,
"category" : [
{
"name": "category2"
},
{
"name": "category3"
}
]
},
{
"_id" : 3,
"category" : [
{
"name": "category3"
},
{
"name": "category1"
}
],
"event": [
{
type: "mouse"
}
]
}

我需要按不同的类别名称类型进行分组,并计算是否存在事件以获取以下文档:

{ "category1": total_count: 2,
"category2": total_count: 0,
"category3": total_count: 1}

任何帮助将不胜感激。

试试这个,它对我有用:

db.getCollection('coll').aggregate([
{$unwind: "$category"},
{$group :{
_id : "$category.name",   
total_count : {$sum : 1}
}
}]) 

最新更新