mongodb - MongoDB - double $group 使第二个 ObjectID 成为嵌套文档
问题描述
我有一个集合,在展开后具有这种结构(我删除了我认为与问题无关的信息)
{
"_id" : ObjectId("1"),
"Members" : {
"City" : "New York"
},
"Group_name" : "Group A"
}
{
"_id" : ObjectId("2"),
"Members" : {
"City" : "Seattle"
},
"Group_name" : "Group A"
}
{
"_id" : ObjectId("3"),
"Members" : {
"City" : "Seattle"
},
"Group_name" : "Group A"
}
{
"_id" : ObjectId("4"),
"Members" : {
"City" : "New York"
},
"Group_name" : "Group B"
}
{
"_id" : ObjectId("5"),
"Members" : {
"City" : "Los Angeles"
},
"Group_name" : "Group B"
}
{
"_id" : ObjectId("6"),
"Members" : {
"City" : "Los Angeles"
},
"Group_name" : "Group B"
}
我使用双对象 ID 来获得这样的结果:
{ "_id" : { "group" : "A", "city" : "New York" }, "totalMembers" : 1 }
{ "_id" : { "group" : "A", "city" : "Seattle" }, "totalMembers" : 2 }
{ "_id" : { "group" : "B", "city" : "New York" }, "totalMembers" : 1 }
{ "_id" : { "group" : "B", "city" : "Los Angeles" }, "totalMembers" : 2 }
我希望能够获得具有以下结构的文档:
{
"_id" : "A",
"Cities" : {
"New York" : 1,
"Seattle" : 2
}
}
{
"_id" : "B",
"Cities" : {
"New York" : 1,
"Los Angeles" : 2
}
}
到目前为止,这是我的代码,我无法按“组”分组,然后按“城市”分组
db.Users_Group.aggregate([
{"$unwind":"$Members"},
{"$group":{"_id":{"group":"$Group_Name","City":"$Members.City"},"totalUsers":{"$sum":1}}},
{"$group":{"_id":"$_id.grupo","total":{"$sum":1}}}
] )
有了这个,我得到了该组中未按城市分隔的所有成员的总和。如何在每个组中嵌套包含该城市用户总数的城市文档?感谢您对此的任何帮助。提前致谢。
解决方案
您需要再运行一次并为$arrayToObject$group
准备数据,该数据采用一对数组:k-v
db.collection.aggregate([
// your current aggregation stages
{
$group: {
_id: "$_id.group",
Cities: { $push: { k: "$_id.city", v: "$totalMembers" } }
}
},
{
$project: {
_id: 1,
Cities: { $arrayToObject: "$Cities" }
}
}
])
推荐阅读
- javascript - 在导出期间显示更新进度
- android - 如何为 android 架构组件生命周期事件添加单元测试?
- google-sheets - 带有排名的电子表格数据透视表
- angular - 如何检查警卫中的skipLocationChange?
- firebase - 这种重新加载方法是如何工作的,它到底是用来做什么的?
- typescript - 如何在具有多个 tsconfig.json 的项目中设置路径属性?
- java - Netbean 正在打开 Junit3 模板而不是 Junit4
- angular - 从 api 获取的数据中的角度材料中的分页
- c# - Xamarin C# MainAvtivity.Intent 为空
- windows - 克隆 repo 时 remote-https 不是 git 命令