Mongodb 3.4.7分组后聚合一个字段的唯一计数

时间:2018-07-02 12:01:28

标签: mongodb aggregation-framework

我有

{
"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 }

我对此也有一些匹配条件,此处未提供。

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'}
     }}
])