mongodb - 如何在mongoDB中获取记录计数分组字段值?
问题描述
我想按组字段(国家/地区)值获取记录总数,我正在尝试但没有得到它。下面是我的代码:-
var company_id= company._id
FollowCompany.aggregate(
[
{
$match: { company_id :company_id } // company_id field in database and user param
},
{
$group:
{
_id: "$country" , // need to group by country in database
count: { $sum:1 },
}
},
{ $sort : { entry_date : -1 } },
]).exec(function(err, followerData) {
console.log(followerData)
})
它显示空结果,有什么帮助或想法吗?提前致谢
解决方案
我找到了解决方案,现在我想将 _id 字段显示为国家/地区,任何解决方案,下面是我的代码:
FollowCompany.aggregate(
[
{
$match: {company_id:""+company_id+""}
},
{
$group:
{
_id: "$country" ,
count: { $sum:1 },
}
},
{ $sort : { _id : 1 } },
])
输出是
{
"_id": "India",
"count": 1
}
我想要这样
{
"country": "India",
"count": 1
}
推荐阅读
- nginx - nginx access_log 路径正确,但不产生任何日志
- php - 显示缩略图宽度小于 200 像素的帖子
- google-apps-script - clearcontent 行上的某些单元格/列包含某些 tex
- google-apps-script - 如何使用谷歌应用脚本将一系列数据复制到另一个谷歌工作表?
- wordpress - 将 WordPress 用户电子邮件传递给日历小部件
- javascript - 如何对强制重排的 Javascript 操作进行分组?
- python-3.x - 如何通过双端队列旋转队列?
- typescript - 无法在 VSCode 中的 typescript react 文件中键入 css 属性
- flutter - 如何解决不同尺寸的 UI?Mediaquery 不能解决文本 UI
- sql - postgresql中如何处理json数据并放入数组