Question

Yet another mongodb question for me:

I'm trying to $group some items in an array in my mongodb for all users: Here is a document

        {
         name: "Foo Bar",
         groups:[{
              groupName: "Group D",
              score:[2,1]
            },
            {
              groupName: "Group D",
              score:[3,0]
            },
            {
              groupName: "Group C",
              score:[2,2]
            }]

    }

All the users have the same structure, only the scores change. I want to go over all the users, and return all their "Group D" objects, grouped together with their name - the result of my solution needs to look like this:

 result:
    [{name:"Foo Bar", 
       groups:[{
                      groupName: "Group D",
                      score:[2,1]
               },
               {
                      groupName: "Group D",
                      score:[3,0]
               }]
   },{//*More users*//}]

So I know I need to $group, and probably $all , $aggregate , $wind ...

But all the examples I see are towards the query part and not the projection part of the find(). I need to get this info from ALL users, but I don't want to handle all my users and start scanning for the info outside the mongodb...In other words - complex projection, is it possible?

Was it helpful?

Solution

Fairly simple:

db.collection.aggregate([
    // Unwind the array
    { "$unwind": "$groups" },

    // Match the elements you want
    { "$match": { "groups.groupName": "Group D" } },

    // Group back to the original form
    { "$group": {
        "_id": "$_id",
        "name": { "$first": "$name" },
        "groups": { "$push": "$groups" }
    }}
])

And that should do it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top