使用嵌套元素的MongoDB聚合

时间:2015-04-17 11:09:53

标签: mongodb aggregation-framework

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

"_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
    ]
}

我想按访问者分组。找到哪个拥有者访问次数最多,我试过这个:

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

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

1 个答案:

答案 0 :(得分: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
}