This is the aggregation function as we executed it in the last lecture with group.
Now as you saw there, we lost all the existing data
but that made sense because we grouped together our data
and if you do such a grouping, you will typically be fine with losing the data.
Now of course when we ran that method here, when we ran our pipeline like this, what we got was a bunch
of outputs in a totally unsorted order,
of course we can also sort and now here is already something where you see the advantage of the aggregation
pipeline.
You can sort at any place here of course but we probably want to sort by total persons now,
so this is something which we only can do after having grouped,
we can't run the sort on our input data because that will just be the person documents and there, we
can sort on things like the age and so on
but we can sort on the amount of persons in a state because that is a result we only derived here.
So what we can do here is we can of course add a new pipeline stage, the sort
stage and the sort stage also takes a document as an input to define how the sorting should happen
and you can simply sort as you also sorted before. So you can say I now want to sort by
and now of course you can say total persons, referring to that field which we introduced in the last
pipeline stage.
This is not a field existing in our input dataset but this does not matter because as you learned, each
pipeline stage passes some output data to the next stage and that output data is the only data that
next stage has.
So this sort stage does not have access to the original data as we fetched it from the collection,
it only has access to the output data of our group stage.
So there, we will have a total persons field and we can now sort by this in descending order to have
the highest values first.
If we now copy that over into our shell, we indeed see that we have some sorted results here,
so you see we got a bunch of results,
that is the first one with 33 persons in this state,
then we got 22 persons this state, here we got a bit of a longer state name hence the different output
but there we got 24 persons.
So this looks alright to me,
we see the sorting works and the interesting thing here really is that the sorting was done on the
output of our previous stage,
so on the output of the group stage. And I hope this already shows you that you have a lot of power with
these tools already because this is essentially a kind of operation we couldn't do with the normal find
method because there, we can't group and then sort on the result of our group. We would have to do that in
the client side code with just find, well with aggregate we can run it on the mongodb server and
then simply get back the data in the client that we need in our client to work with.