Field not showing in Mongoose aggregation

╄→尐↘猪︶ㄣ 提交于 2019-12-31 05:36:06

问题


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 },
}
(...)


来源:https://stackoverflow.com/questions/12782105/field-not-showing-in-mongoose-aggregation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!