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

有了这个,我得到了该组中未按城市分隔的所有成员的总和。如何在每个组中嵌套包含该城市用户总数的城市文档?感谢您对此的任何帮助。提前致谢。

标签: mongodbaggregation-framework

解决方案


您需要再运行一次并为$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" }
        }
    }
])

蒙戈游乐场


推荐阅读