Mongodb聚合嵌套组

时间:2017-02-25 13:05:45

标签: javascript node.js mongodb mongoose aggregation-framework

我已在我的收藏中分配了人员,状态,如下所示

[
 {"ASSIGN_ID": "583f84bce58725f76b322398", "STATUS": 1},
 {"ASSIGN_ID": "583f84bce58725f76b322398","STATUS": 4},
 {"ASSIGN_ID": "583f84bce58725f76b322398","STATUS": 4},
 {"ASSIGN_ID": "583f84bce58725f76b322398","STATUS": 3},
 {"ASSIGN_ID": "583f84bce58725f76b322311","STATUS": 1},
 {"ASSIGN_ID": "583f84bce58725f76b322311","STATUS": 3},
 {"ASSIGN_ID": "583f84bce58725f76b322322","STATUS": 1},
 {"ASSIGN_ID": "583f84bce58725f76b322322","STATUS": 4}
]

我希望按 ASSIGN_ID 对此数据进行分组,并在状态计数内对每个状态进行分组。

[  
   {  
      "ASSIGN_ID":"583f84bce58725f76b322398",
      "STATUS_GROUP":[  
         {  
            "STATUS":1,
            "COUNT":1
         },
         {  
            "STATUS":3,
            "COUNT":1
         },
         {  
            "STATUS":4,
            "COUNT":2
         }
      ]
   },
   {  
      "ASSIGN_ID":"583f84bce58725f76b322311",
      "STATUS_GROUP":[  
         {  
            "STATUS":1,
            "COUNT":1
         },
         {  
            "STATUS":3,
            "COUNT":1
         }
      ]
   },
   {  
      "ASSIGN_ID":"583f84bce58725f76b322322",
      "STATUS_GROUP":[  
         {  
            "STATUS":1,
            "COUNT":1
         },
         {  
            "STATUS":4,
            "COUNT":1
         }
      ]
   }
]

但是,我有编写代码,它只按 STATUS 分组。请在下面找到查询。

Inspection.aggregate([
    {$group: {
    "_id": '$STATUS',
    "count" :  { $sum : 1 }}}], function (err, result) {
}});

请帮我解决这个问题。

1 个答案:

答案 0 :(得分:12)

使用此命令,它适用于您的示例案例, 希望它能解决你的问题,

db.testCollection.aggregate([{
    $group: {
        _id: {
            ASSIGN_ID: "$ASSIGN_ID",
            STATUS: "$STATUS"
        },
        count: {
            "$sum": 1
        }
    }
}, {
    $group: {
        _id: "$_id.ASSIGN_ID",
        STATUS_GROUP: {
            $push: {
                STATUS: "$_id.STATUS",
                count: "$count"
            }
        }
    }
}])

在shell中输出:

{
    "_id": "583f84bce58725f76b322398",
    "STATUS_GROUP": [{
        "STATUS": 3,
        "count": 1
    }, {
        "STATUS": 4,
        "count": 2
    }, {
        "STATUS": 1,
        "count": 1
    }]
}, {
    "_id": "583f84bce58725f76b322311",
    "STATUS_GROUP": [{
        "STATUS": 3,
        "count": 1
    }, {
        "STATUS": 1,
        "count": 1
    }]
}, {
    "_id": "583f84bce58725f76b322322",
    "STATUS_GROUP": [{
        "STATUS": 1,
        "count": 1
    }, {
        "STATUS": 4,
        "count": 1
    }]
}