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.