Count for distinct values for a certain id in MongoDB

时间:2019-03-19 15:15:55

标签: mongodb aggregation

I am learning MongoDB aggregation for our data analysis. The sample dataset is as follows:

{ "_id" : ObjectId("5c8fa906cd5591004c2db5f9"), "id" : 49893861, "cate_id" : "81614" }
{ "_id" : ObjectId("5c8fa906cd5591004c2db602"), "id" : 49893861, "cate_id" : "1102" }
{ "_id" : ObjectId("5c8fa906cd5591004c2db606"), "id" : 49893861, "cate_id" : "1102" }

The desired result should be:

{
  "id": 49893861,
  "categories": [
    {
      "cate_id": "1102",
      "count": 2
    },
    {
      "cate_id": "81614",
      "count": 1
    },
  ]
}

I am wondering how to achieve this using the correct MongoDB aggregation framework command. Thank you!

1 个答案:

答案 0 :(得分:0)

您必须在此处使用两个$group阶段。首先使用Event<T>idcate_id的文档数量,其次使用count

id