猫鼬聚合中未显示字段 [英] Field not showing in Mongoose aggregation

查看:54
本文介绍了猫鼬聚合中未显示字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试统计所有不同的部门.我希望结果包含deptType,deptName和计数.分组有效,结果显示deptType和dCount,但不显示deptName.知道为什么吗?

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?

我的数据如下:

{
  "_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"}
]
}

和我的Mongoose聚合命令如下:

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) {}
);

谢谢大家.

推荐答案

对不起,很傻:

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

这篇关于猫鼬聚合中未显示字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆