如何在mongoose中使用更多$ group

时间:2015-11-30 10:32:00

标签: node.js mongodb mongoose

[

{
    "_id":"56569bff5fa4f203c503c792",
    "Status":{
        "StatusID":2,
        "StatusObjID":"56559aad5fa4f21ca8492277",
        "StatusValue":"Closed"
    },
    "OwnerPractice":{
        "PracticeObjID":"56559aad5fa4f21ca8492291",
        "PracticeValue":"CCC",
        "PracticeID":3
    },
    "Name":"AA"
},
{
    "_id":"56569bff5fa4f203c503c792",
    "Status":{
        "StatusID":2,
        "StatusObjID":"56559aad5fa4f21ca8492277",
        "StatusValue":"Open"
    },
    "OwnerPractice":{
        "PracticeObjID":"56559aad5fa4f21ca8492292",
        "PracticeValue":"K12",
        "PracticeID":2
    },
    "Name":"BB"
}

在上面的json回复中,

如何将PracticeValue,StatusValue分组为单个函数,

以下代码仅用于分组StatusValue,请帮助如何使用相同的功能对Practice值进行分组,

Opp.aggregate([
     {$group: {
         _id: '$Status.StatusValue',
         count: {$sum: 1}
     }}
], function (err, result) {
    res.send(result);
});

我的回答是,

[
    {
        "_id":"Deleted",
        "count":0
    },
    {
        "_id":"Open",
        "count":1
    },
    {
        "_id":"Closed",
        "count":1
    }
]


please help me, how to use more then $group function..

1 个答案:

答案 0 :(得分:1)

您可以按以下方式分组多个字段:

var resultAggr = {Status: [], Practice: []};

Opp.aggregate(
  [
     {$group: { _id: '$Status.StatusValue', count: {$sum: 1} }}
  ], function (err, statusResult) {
      resultAggr.Status = statusResult;
      Opp.aggregate(
      [
         {$group: { _id: '$OwnerPractice.PracticeValue', count: {$sum: 1} }}
      ], function (err, practiceResult) {
          resultAggr.Practice = practiceResult;
          res.send([resultAggr])
      });
});