我有
{
"statement": {
“activity”: {
"definition": {
“name”: “ACT_NAME1”
}
},
"actor": {
"name": "User 2”
}
},
"statement": {
“activity”: {
"definition": {
“name”: “ACT_NAME2”
}
},
"actor": {
"name": "User 1"
}
},
"statement": {
“activity”: {
"definition": {
“name”: “ACT_NAME2”
}
},
"actor": {
"name": "User 1"
}
},
"statement": {
“activity”: {
"definition": {
“name”: “ACT_NAME1”
}
},
"actor": {
"name": "User 1"
}
}
}
我想按statement.activity.definition.name分组,并在每组中计算actor.name的不同计数。该怎么做?
{ activity: ACT_NAME1
unique_actor_count: 2 }
{ activity: ACT_NAME2
unique_actor_count: 1 }
我对此也有一些匹配条件,此处未提供。
答案 0 :(得分:1)
使用$addToSet
将分组的项目累积到一个集合(唯一元素)中
document.collection.aggregate([
{$match: {}},
{$group:
{
_id: '$statement.activity.definition.name',
actors: {$addToSet: '$statement.actor.name'}
}
},
{$project: {
_id: '$_id',
actors: '$actors',
uniqueActorsCount: {$size: '$actors'}
}}
])