CoderAnswer - 程序员编程问答

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

by @Noah Kleiner

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 by @Noah Kleiner

我明白了。

d​​b.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"
                        }
                    ]
                }
            ]
        }
    ]
}

相关问题