So I'm still in that same database
I was in the end of the last video and let's now use that aggregate framework.
We use it in a very simple way, instead of running find on persons or find one,
we now run aggregate and we already saw this one time in this course already with look up in the schemas
and relations module. The aggregate method takes an array and it takes an array because we define
a series of steps that should be run on our data.
The first step will receive the entire data right from the collection you could say
and the next step can then do something with the data returned by the first step and so on.
Now one important piece of information, aggregate does not go ahead, fetch all the data from the database
and then give it to you and then do something on it,
of course the first step runs on the database and can take advantage of indexes,
so if you filter in the first step or you sort there, you can take advantage of your indexes,
so you don't have to fetch all the documents just because you're using aggregate. Aggregate as find executes
on the mongodb server and therefore can take advantages of things like indexes
and it will.
So what could be a first step that we run? Now to make this a bit easier to read, I'll type this in multiple
lines by not closing that expression immediately
and the first step is then a document, every step is a document
I should say. Now the first step here could be a match phase and match essentially is just a filtering step,
so you define some criteria on which you want to filter your data in that persons collection.
Now you can filter here, in the same way you can filter in find,
so all the things you learn there on how you can query documents, how you can match for greater than
values and so on applies here too.
So what we could do here is we could for example and if we have a look at our data structure again, we
could for example look at females only.
So to do that, let's simply add a condition here where we say gender should be equal to female.
Now we can already finish our pipeline at this point if we want to,
we can close the square brackets around our stages and close the parentheses of aggregate and I get
back a cursor here,
you can tell by the fact that I see type it here too.
So just like the find method, the aggregate method returns a cursor,
so you have to use it as you use the cursor returned by the find method in your application.
Besides that, we can also pretty print that
and now you see, well some results at least of the results we fetched and we should only see females
in there.
This was of course only one step, the match step and the match step is not that exciting because there,
we as I said query it exactly the same way we can query in the find method or we filter in the same
way I should say. More interesting is the group stage so
let's take a look at that in the next lecture.