- [Instructor] If you have a document
with an array you can use the $unwind stage
to create one output document for each array element.
Let's try that within the terminal.
Again, we are going to be using the inventory collection.
So, let's just remind ourselves what that looks like.
Okay, cool, and here we are going to unwind
the variations array,
so that we can get a document for each car variation.
Okay, the way we are going to do that
is by first specifying the collection
on which we're going to run the aggregation,
then we'll use the aggregate method,
and inside it, you know it, there's going to be an array,
with a document for the $unwind stage.
And to the $unwind stage we are going to pass a string,
which contains the variations field name.
And to that we are going to have to add
a dollar sign at the beginning.
Okay, let's try this.
Awesome, we now have individual documents
for each car variation.
That's often very useful,
for example, we can now match on only purple car variations.
So, let's do that.
And the way we do that is inside the aggregation pipeline,
we're going to add another pipeline stage,
by adding another document to this array.
And inside this document,
we're going to add a $match stage,
and as the argument to that stage operator,
we're going to pass in the variations.variation field.
Okay, and we're going to match on the color purple.
That gives us nothing, that's because I have a typo.
Right, so let's just briefly fix that.
Great, now we have all purple cars.
So, there is something about this
that isn't quite optimal yet.
If you think about this
from how this data would get processed,
we would unwind all documents,
even if we know that that document
doesn't have a variation that is purple.
That is not performant if you're going to do this a lot.
So, in this case, what you should do,
is you should actually add an additional match stage
before the unwind stage,
because MongoDB can directly filter out
any of the documents that don't even have a purple variation
in the variations array, before unwinding it.
So let's do that.
Go into it again, add this match stage,
and then say variations.variation,
and say it has to be purple.
Okay, cool.
So this is going to be a lot more performant.