1

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?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks - can you explain please what $first does in this query - because in the source it says - "Only use $first when the $group follows a $sort operation. Otherwise, the result of this operation is unpredictable."
@orepor Usually that would be the case, but since this is grouping by _id and does not traverse documents there is nothing to sort. So this is just taking your existing field in the document and presenting it in the result with the same structure your original document had. There is only one field per document so $first is appropriate.

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.