我的收藏品看起来像这样:
{
"_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}
任何帮助都将受到高度赞赏。
答案 0 :(得分:1)
试试这个,它对我有用:
db.getCollection('coll').aggregate([
{$unwind: "$category"},
{$group :{
_id : "$category.name",
total_count : {$sum : 1}
}
}])