简体   繁体   中英

MongoDB Aggregation using nested element

I have a collection with documents like this:

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

I want to group by visitors.owner to find which owner has the most visits, I tried this:

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

But I always get count = 0 and visits not corresponding to one owner :/
Please help

Try the following aggregation pipeline:

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

Using the sample document you provided in your question, the result is:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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