从数组中拆分和聚合计数

时间:2017-01-09 06:37:47

标签: mongodb

我的MongoDB实例中的文档如下所示

{
  ...
  regions: ["Region-West", "Region-HC"],
  care_levels: ["Memory Care"],
  ...
}
{
  ...
  regions: ["Region-West", "Region-SC"],
  care_levels: ["Physical Rehab"],
  ...
}
{
  ...
  regions: ["Region-East", "Region-NC"],
  care_levels: ["Physical Rehab"],
  ...
}

区域和护理级别都是字符串数组。我想执行一组特定区域和care_levels映射的文档计数。例如 -

Region-East, Physical Rehab => 20
Region-East, Memory Care => 20
Region-West, Memory Care => 30

我正在运行以下查询

db.incidents.aggregate([
    {$match:
    {"care_levels": { $size: 1, $in: ["Memory Care", "Physical Rehab"] }},
    },
    { "$group": {
        "_id": {
            "regions": "$regions",
            "care_levels": "$care_levels",
        },
        "incidentCount": { "$sum": 1 }
    }},
])

我得到结果

{ "_id" : { "regions" : [ "Region-East", "Region-HC" ], "care_levels" : [ "Memory Care" ] }, "incidentCount" : 2409 }
{ "_id" : { "regions" : [ "Region-East", "Region-HC" ], "care_levels" : [ "Physical Rehab" ] }, "incidentCount" : 2459 }
{ "_id" : { "regions" : [ "Region-East", "Region-SC" ], "care_levels" : [ "Memory Care" ] }, "incidentCount" : 2504 }
{ "_id" : { "regions" : [ "Region-West", "Region-HC" ], "care_levels" : [ "Memory Care" ] }, "incidentCount" : 2382 }
{ "_id" : { "regions" : [ "Region-West", "Region-HC" ], "care_levels" : [ "Physical Rehab" ] }, "incidentCount" : 2475 }
{ "_id" : { "regions" : [ "Region-East", "Region-SC" ], "care_levels" : [ "Physical Rehab" ] }, "incidentCount" : 2478 }
{ "_id" : { "regions" : [ "Region-South", "Region-HC" ], "care_levels" : [ "Physical Rehab" ] }, "incidentCount" : 2405 }
{ "_id" : { "regions" : [ "Region-West", "Region-SC" ], "care_levels" : [ "Memory Care" ] }, "incidentCount" : 2490 }
{ "_id" : { "regions" : [ "Region-West", "Region-SC" ], "care_levels" : [ "Physical Rehab" ] }, "incidentCount" : 2433 }
{ "_id" : { "regions" : [ "Region-South", "Region-HC" ], "care_levels" : [ "Memory Care" ] }, "incidentCount" : 2465 }

我想过滤掉我不关心的地区。在这种情况下,我不希望Region-SC和Region-HC的分割以及Region-West / East / South的分数应该是Region-SC和Region-HC分割的值的总和。

特别是在这种情况下,我想要值

Region-East, Memory Care => (2409 + 2504)
Region-West, Memory Care => (2382 + 2490)

如何通过进一步聚合实现这一目标?

1 个答案:

答案 0 :(得分:0)

我开始意识到一个简单的$ unwind,我需要的是什么。我之前使用了错误的语法因此出现了问题。