我有一个集合,在展开后具有这种结构(我删除了我认为与该问题无关的信息)
{
"_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}}}
] )
通过此操作,我得到了该组中所有成员的总和,没有城市分开。如何在每个组中嵌套城市的文档以及该城市的用户总数?感谢对此的任何帮助。预先感谢。
答案 0 :(得分:2)
您需要再运行$group
并为$arrayToObject准备数据,该数据需要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" }
}
}
])