So in the last lecture you saw how you can push elements into newly created arrays and I will emphasize
this again, that the values you push don't have to be arrays themselves.
We could have pushed the age or the name, that would have worked too
and then we would have all hobbies or a different name then which would be an array of all the ages
that are in the group or all the names that are in the group,
so this would have worked too.
I however want to have these values in all hobbies but not in their nested arrays
and for that, I will add a new pipeline stage which we haven't seen before and that is the unwind stage.
The unwind stage is always a great stage when you have an array of which you want to pull out the elements.
Now to understand what unwind does, I'll temporarily move my grouping out of there so that I can just copy
that later and I'll complete the unwind stage.
Unwind has two different syntaxes and you can check the official docs for all the details as always,
in its most common usage,
you just pass the name of a field that holds an array,
so hobbies,
remember we get our own initial documents as an input to this stage and now, we just unwind on hobbies.
Now what does unwind do?
Well let's take that stage and let's see. If I execute this,
you see what I get back are a couple of documents more than we originally had because now we have
a document Max with hobbies sports and we have Max again with hobbies cooking.
So what unwind does is it basically flattens the array by repeating the document
that held the array as often as needed to merge it with the array elements. So the original array of Max
simply has sports and cooking,
therefore Max was repeated twice,
we get two new documents, Max with sports and Max with cooking and the same is true for all other elements.
So where group merges multiple documents into one, unwind takes one document and spits out multiple
documents
and now with that, we can group again
but now we can simply take hobbies which is no longer an array but a single value.
So if I now bring back my group stage, I can leave it as it is
but now you will see, if I repeat this,
I still only have two groups because the ages haven't changed
but now you see all hobbies holds
just my array values and not the embedded arrays.
However you can also see that we can have duplicate values,
so what can we do about that?