如何进行多阶段嵌套聚合?

时间:2019-05-13 18:43:26

标签: mongodb aggregation-framework

我目前有一个名为people的数据库。

每个文档都包含以下属性:citystatecountry

示例:

{
    "_id": "5cd80e1ab3ee820fd9416301",
    "name": "John Doe",
    "city": "New York City",
    "state": "NY",
    "country": "US"
}

我想做的是在每个城市,每个州,每个国家都派出一批人。

示例:

{
    "US": {
        "NY": {
            "New York City": [
                {
                    "_id": "5cd80e1ab3ee820fd9416301",
                    "name": "John Doe"
                }
            ]
        }
    }
}

我发现this answer很近,但我不知道如何使它工作。

1 个答案:

答案 0 :(得分:0)

我知道了。

db.people.aggregate([
    {
        $group: {
            _id: {
                country: "$country",
                state: "$state",
                city: "$city",
                person: "$$ROOT"
            }
        }
    },
    {
        $group: {
            _id: {
                country: "$_id.country",
                state: "$_id.state",
                city: "$_id.city",
                person: "$_id.person"
            },
            people: {
                $push: "$_id.person"
            }
        }
    },
    {
        $group: {
            _id: {
                country: "$_id.country",
                state: "$_id.state"
            },
            cities: {
                $push: {
                    city: "$_id.city",
                    people: "$people"
                }
            }
        }
    },
    {
        $group: {
            _id: {
                country: "$_id.country"
            },
            states: {
                $push: {
                    state: "$_id.state",
                    cities: "$cities"
                }
            }
        }
    },
    {
        $project: {
            _id: 0,
            country: "$_id.country",
            states: "$states"
        }
    }
]);

结果将如下所示:

{
    "country": "US",
    "states": [ 
        {
            "state": "NY",
            "cities": [ 
                {
                    "city": "New York City",
                    "people": [ 
                        {
                            "_id": "5cd80e1ab3ee820fd9416301",
                            "name": "John Doe",
                            "city": "New York City",
                            "state": "NY",
                            "country": "US"
                        }
                    ]
                }
            ]
        }
    ]
}