database - mongodb GROUP BY 和 COUNT 文档中的数组
问题描述
给定:集合中的单个文档。Document 包含一个数组。(即集合中仅存在一个文档条目)
期望:在city
和上执行分组print counts
样本数据:
{
name: "ABC Bank",
hospitalList: [
{city: "Delhi", hspName: "EEE hospital"},
{city: "Delhi", hspName: "FFF hospital"},
{city: "Surat", hspName: "MMM hospital"},
{city: "Noida", hspName: "GGG hospital"},
{city: "Surat", hspName: "HHH hospital"},
{city: "Surat", hspName: "NNN hospital"},
{city: "Surat", hspName: "PPP hospital"},
]
}
预期输出:
Delhi - 2
Noida - 1
Surat - 3
试过(但没有用)
$group: {
_id: "hospitalList.city",
count: { $sum: 1 }
}
解决方案
- $match - 匹配文件银行名称
- $unwind - 在自己的文档中拆分对象数组
- $group - 按城市分组,然后计算计数
db.collection.aggregate([
{
$match: {
name: "ABC Bank"
}
},
{
"$unwind": "$hospitalList"
},
{
$group: {
_id: "$hospitalList.city",
count: {
$sum: 1
}
}
}
])
Mongo 游乐场:https ://mongoplayground.net/p/Ac7RkJd7vU9
根据预期的输出:Mongo 游乐场:https ://mongoplayground.net/p/zeqB7P-BYmI
推荐阅读
- c# - 如何修复“短语”不能为空字符串。参数名称:词组'?
- r - geom_map fill = 变量将每个值拆分为单独的颜色而不是渐变
- angular - 创建已弃用:从 v5 开始使用新签名 Injector.create(options)(弃用)
- python - 查找不包含特定数字的最长序列
- c# - 如何从 Google 登录令牌 WebApi 核心读取用户信息
- android - Android studio jarsigner:与密钥关联的密钥不是私钥
- php - 检查数组是否在php中具有除null以外的值的最佳方法是什么?
- c# - 无法识别的元素 unitTestProvider
- c++ - 如何在 C++ 中将函数作为参数传递
- javascript - 为什么 React 在提升状态时运行缓慢?