mongodb - MongoDB Shell 聚合管道未按我希望的方式分组
问题描述
设计并实施 MongoDB 聚合管道,以按州显示在美国设有办事处的所有公司的员工总数。
我原来的解决方案是这样的:
db.research.aggregate([
{ $match: { "offices.country_code": "USA" } },
{ $group: { _id: "$offices.state_code", total: { $sum: "$number_of_employees" } } }
])
问题是每个文档可以有多个offices
,导致许多返回的结果是不同状态代码的组合。例如,这些是一些结果:
{ "_id" : [ null, "IL" ], "total" : 61 }
{ "_id" : [ "NY", "CA", null ], "total" : 20 }
{ "_id" : [ "UT", "CA", "NY", null ], "total" : 0 }
{ "_id" : [ null, "GA", null, null ], "total" : 0 }
{ "_id" : [ "WA", "WA", "NY", "CA", "MA", null ], "total" : 1650 }
{ "_id" : [ "TX", "IL" ], "total" : 22 }
{ "_id" : [ "MA", "NV" ], "total" : 0 }
{ "_id" : [ "NY", "CO", "CA" ], "total" : 0 }
{ "_id" : [ "MA", "MA" ], "total" : 25 }
{ "_id" : [ "VA", "NY", "CA", null, null ], "total" : 5 }
{ "_id" : [ "CA", "CA", "NY", "IL", "CA", null, null ], "total" : 0 }
{ "_id" : [ "CA", null, "NY", "CA", null ], "total" : 50 }
{ "_id" : [ "CA", "ME" ], "total" : 2 }
{ "_id" : [ "MA" ], "total" : 255864 }
{ "_id" : [ "DE" ], "total" : 409 }
{ "_id" : [ "DC", "CA", "VA" ], "total" : 7000 }
{ "_id" : [ "ND" ], "total" : 18 }
{ "_id" : [ null, null, "VA", null, null, null, "VT", null, null ], "total" : 0 }
{ "_id" : [ "NC", null, null, null ], "total" : 290 }
{ "_id" : [ "SC", "NY" ], "total" : 0 }
相反,我希望将每个“state_code”与该州的员工人数分开列出。如果一个文档有多个状态代码,它应该计入每个状态代码。例如,如果一个文档有 1000 名员工并且州代码为“NY”和“CA”,则 1000 应计入这两个总和。我不希望它像当前那样列出状态代码的唯一组合。有任何想法吗?
解决方案
组前解构offices
数组,
$unwind
解构offices
数组
db.research.aggregate([
{ $match: { "offices.country_code": "USA" } },
{ $unwind: "$offices" },
{
$group: {
_id: "$offices.state_code",
total: { $sum: "$number_of_employees" }
}
}
])
推荐阅读
- excel - 如何在具有额外(非日期)列的数据透视表中对日期进行分组
- python - range() 中的计数器无法识别为整数
- javascript - 如果修改了数据库表,则对 Vue 组件进行实时更改
- python - 解析 .txt 文件时出现问题
- php - 获取第一个产品的第一个标签列表
- c# - C# 程序从命令行打开 Word docx(不是 doc),在 Jenkins 中失败
- django - Django ORM相关管理器为过滤器添加默认值
- types - 进入
vs Iterator 用于在线算法 - spring-boot - 无法自动接线。找不到“InstructionRepository”类型的 bean
- java - 用于 VSCode 调试器的 Tomcat 在步骤期间未显示变量值