Mongodb:计算由另一个字段分组的字段中的多个值

时间:2018-04-16 17:05:09

标签: mongodb-query

我有一个如下集合

{"country":"US","city":"NY"}
{"country":"US","city":"AL"}
{"country":"US","city":"MA"}
{"country":"US","city":"NY"}
{"country":"US","city":"MA"}
{"country":"IN","city":"DL"}
{"country":"IN","city":"KA"}
{"country":"IN","city":"DL"}
{"country":"IN","city":"DL"}
{"country":"IN","city":"KA"}

并期待输出

{ "data": { "US": {"NY": 2,"AL": 1,"MA": 2 },
        "IN": {"DL": 3,"KA": 2 }}
}

下面是我尝试的mongodb查询,我能够在国家级别获得计数,但不能在州级别获得。请帮助我纠正以下查询以获取州级数据。

db.country_dash.aggregate([
        {"$group": {
            "_id":"$country",
            "state": {"$addToSet": "$state"} 
        }},
        {"$project": {
            "_id":0,
            "country":"$_id",
            "state": {"$size": "$state"}
        } }
        ])

1 个答案:

答案 0 :(得分:0)

db.country_dash.aggregate(

    // Pipeline
    [
        // Stage 1
        {
            $group: {
                _id: {
                    city: '$city'
                },
                total: {
                    $sum: 1
                },
                country: {
                    $addToSet: '$country'
                }
            }
        },

        // Stage 2
        {
            $project: {
                total: 1,
                country: {
                    $arrayElemAt: ['$country', 0]
                },
                city: '$_id.city',
                _id: 0
            }
        },

        // Stage 3
        {
            $group: {
                _id: '$country',
                data: {
                    $addToSet: {
                        city: '$city',
                        total: '$total'
                    }
                }
            }
        },

    ]



);