Now with all the projections we did thus far, let's now add another stage again
after all our projections,
so here I'll add another group stage because this is another common scenario that you first want to restructure
your data,
recalculate some fields as we are doing it,
we're adding brand new fields which didn't exist before
and then you want to group on these derived fields.
In my case here I want to group on the birth date and yes, this was available before but not as a date
at least,
we converted it and I will now take advantage of this conversion.
So I'll take advantage of my birth date which is now stored as a date in the group stage here.
We saw the group stage before, we add _id here and then we define by which value we want to
group.
Now here I want to group by birthdate but not by the date but let's say by the year, so birth year is by
which I want to group,
therefore we add a document here and then the operator is the ISO year operator which basically retrieves
the year out of a date.
So the date then is stored in $birthdate pointing at my birth date field of course
and now what do I want to do when grouping these documents?
Well I want to calculate how many persons were born in this year,
so num persons is what I calculate here and I use sum one to basically add one for every document that
goes into that group
and since one document represents one person, I will have the number of persons per birth year here at the
end.
So now with that, whoops this is ISO week year by the way, should be week year.
So now let's copy that, paste it in here and you see, I got my years extracted here as a long number,
this is what mongodb did for me
and I see how many persons were born in there.
Obviously my other projection phases are now rendered a bit useless since I don't take advantage of all the
other fields I added here.
This is just temporary,
I just wanted to show you that you can group on the results of projections.
So here I have the group stage,
let's now maybe even sort and let's sort on the num persons in descending order to start with the most
persons first. If I now enter this here,
now we see most persons in the example dataset were born in 1955.