首页 > 解决方案 > 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 }
}

标签: databasemongodbmongoosemongodb-query

解决方案


  • $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


推荐阅读