MongoDB 使用嵌套元素进行聚合

MongoDB Aggregation using nested element

我有一个 collection 文件是这样的:

"_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 并且访问与一个所有者不对应:/
请帮忙

尝试以下聚合管道:

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
}