Field not showing in Mongoose aggregation

2020-05-06 19:38发布

问题:

I'm trying to get a count of all distinct departments. I'd like the results to contain the deptType, deptName and the count. The grouping works, and results show deptType and dCount, but not deptName. Any idea why?

My data looks like this:

{
  "_id": "10280",
  "city": "NEW YORK",
  "state": "NY",
  "departments": [
         {"departmentType":"01",
          "departmentHead":"Peter"},
         {"departmentType":"02",
          "departmentHead":"John"}
  ]
},
{
  "_id": "10281",
  "city": "LOS ANGELES",
  "state": "CA",
  "departments": [
         {"departmentType":"02",
          "departmentHead":"Joan"},
         {"departmentType":"03",
          "departmentHead":"Mary"}
]
}

and my Mongoose aggregate command like this:

Departments.aggregate(
{  
$project : {"departments.deptType" : 1,
        "departments.deptName" : 1,
        "dCount" : 1  } 
},
{ 
    $match: {"departments.deptType": {$exists: true}} 
},
{  
    $unwind: "$departments" 
},
{ 
    $group: {
        _id: "$departments.deptType",
         dCount: { $sum: 1 },
    }
},
{
$match: { dCount: { $gt: 5 }   }
},
{ $sort: { dCount: -1 } },
{ $limit : 50 },  

function(err, dbres) {}
);

Thank you all in advance.

回答1:

Sorry guys that was silly:

(...)
$group: {
    _id : { dType : "$departments.deptType", 
            dName : "$departments.deptName" 
          },
   dCount: { $sum: 1 },
}
(...)