【问题标题】:MongoDB Aggregation using nested element使用嵌套元素的 MongoDB 聚合
【发布时间】:2015-04-17 19:16:06
【问题描述】:

我有一个包含这样文档的集合:

"_id" : "15",
    "name" : "empty",
    "location" : "5th Ave",
    "owner" : "machine",
    "visitors" : [
        {
            "type" : "M",
            "color" : "blue",
            "owner" : "Steve Cooper"
        },
        {
            "type" : "K",
            "color" : "red",
            "owner" : "Luis Martinez"
        },
        // A lot more of these
    ]
}

我想按visitors.owner 分组以找出访问次数最多的所有者,我尝试了这个:

db.mycol.aggregate(
    [
            {$group: {
                _id: {owner: "$visitors.owner"}, 
                visits: {$addToSet: "$visits"},
                count: {$sum: "comments"}
            }},
            {$sort: {count: -1}},
            {$limit: 1}
    ]
)

但我总是得到 count = 0 并且访问不对应于一个所有者:/
请帮忙

【问题讨论】:

    标签: mongodb aggregation-framework


    【解决方案1】:

    尝试以下聚合管道:

    db.mycol.aggregate([
        {
            "$unwind": "$visitors"
        },
        {
            "$group": {
                "_id": "$visitors.owner",
                "count": { "$sum": 1}
            }
        },
        {
            "$project": {
                "_id": 0,
                "owner": "$_id",
                "visits": "$count"
            }        
        }
    ]);
    

    使用您在问题中提供的示例文档,结果是:

    /* 0 */
    {
        "result" : [ 
            {
                "owner" : "Luis Martinez",
                "visits" : 1
            }, 
            {
                "owner" : "Steve Cooper",
                "visits" : 1
            }
        ],
        "ok" : 1
    }
    

    【讨论】:

    • 成功了!我添加了{$sort: {visits: -1}} 以获得访问次数最多的所有者。非常感谢
    • @Fourat 别担心 :-)
    猜你喜欢
    • 2019-06-26
    • 2021-03-13
    • 2019-01-31
    • 2017-07-26
    • 2017-07-16
    • 2019-07-20
    • 1970-01-01
    • 2020-03-08
    • 2021-08-04
    相关资源
    最近更新 更多