1

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

1 Answer 1

1

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

It worked ! I added {$sort: {visits: -1}} to get the owner with most visits. Thanks a lot
@Fourat No worries :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.