Mongodb在单个聚合中使用多个组运算符

时间:2016-09-27 10:19:30

标签: mongodb mongodb-query aggregation-framework mongodb-aggregation

我正在使用mongodb聚合来获取不同字段的计数。以下是Writers集合中的一些文档: -

mobile

我可以找到{ "title": "Moto G", "manufacturer": "Motorola", "releasing": ISODate("2011-03-00T10:26:48.424Z"), "rating": "high" } { "title": "Asus Zenfone 2", "manufacturer": "Asus", "releasing": ISODate("2014-10-00T10:26:48.424Z"), "rating": "high" } { "title": "Moto Z", "manufacturer": "Motorola", "releasing": ISODate("2016-10-12T10:26:48.424Z"), "rating": "none" } { "title": "Asus Zenfone 3", "manufacturer": "Asus", "releasing": ISODate("2016-08-00T10:26:48.424Z"), "rating": "medium" } manufacturer计数,但这会失败:

rating

输出: -

db.mobile.aggregate([
    {
        $group: { _id: "$manufacturer", count: { $sum: 1 } }
    }, {
        $group: { _id: "$rating", count: { $sum: 1 } }
    }
])

预期输出类似于: -

{
    "_id" : null,
    "count" : 2.0
}

1 个答案:

答案 0 :(得分:4)

我相信您正在进行聚合操作,该操作按<%= movies[i] %>manufacturer键对文档进行分组,然后在rating上再进行一次分组,同时汇总每{{1}的评分类似于以下管道:

manufacturer

示例输出

manufacturer

或者如果您处于更“平坦”或“非规范化”的结果之后,请运行此聚合操作:

db.mobile.aggregate([
    {
        "$group": {
            "_id": { 
                "manufacturer": "$manufacturer",
                "rating": "$rating"
            },
            "count": { "$sum": 1 }
        }
    },
    { 
        "$group": {
            "_id": "$_id.manufacturer",
            "total": { "$sum": 1 },
            "counts": {
                "$push": {
                    "rating": "$_id.rating",
                    "count": "$count"
                }
            }
        }
    }
])

示例输出

/* 1 */
{
    "_id" : "Motorola",
    "total" : 2,
    "counts" : [ 
        {
            "rating" : "high",
            "count" : 1
        }, 
        {
            "rating" : "none",
            "count" : 1
        }
    ]
}

/* 2 */
{
    "_id" : "Asus",
    "total" : 2,
    "counts" : [ 
        {
            "rating" : "high",
            "count" : 1
        }, 
        {
            "rating" : "medium",
            "count" : 1
        }
    ]
}