繁体   English   中英

使用嵌套元素的MongoDB聚合

[英]MongoDB Aggregation using nested element

我有一个包含以下文档的集合:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM