Now there's one last special projection parameter which I want to show you that is related to arrays
and that is the slice operator
you could say. Now I'll repeat my query where I look for movies with a rating average greater than nine,
but now I'll not use $elemMatch your on my genres but I will still use a special value enclosed in
curly braces.
I'll look for a slice of the genres array,
let's say two
and with this yields to me and for that, I will also add some
other projection so that I don't get
everything, I'll also add let's say the name and set it to one because now this will give me a list of items
where I only have the ID because it's in there by default
and I didn't exclude it, then I have the name of the series and then I have the genres but only the
first two elements.
So all these documents can absolutely have more genres assigned to them but I only see the first two
because I use slice two and that can be any number,
you can look for the first three, the first five and you can even use slice in different way.
You can use it in the array form and then the first element is the amount of elements in the array,
so in the genres array which you skip
let's say one and then the second element is the amount of data you want to limit it to, let's say two.
So now we will pull some items from the genres array but we'll skip the first item and then in this
case, return the items 2 and 3,
so the next two items. And now we can see that here we can't directly prove that
but you could of course search for this element,
let's maybe do that. Let's search for firefly by ID,
we see science fiction and western here
but if we quickly use our movies and we look for ID being equal to our objectId and we print this
in a pretty format or don't need to do that,
we can simply project out all the genres,
so just set genres to one.
If I now hit enter,
I get that one entry and we see here, we pulled out science fiction and western,
actually the genres are adventure, science fiction and western.
So we skipped the first value and then we output the next two values,
that is what we did with this syntax, with slice.
So now you have a lot of different ways of controlling what you see, for normal fields it's straight
forward with 1 and 0, for arrays, it's hard to do that with 1 and 0 or impossible to be precise,
so there you got elemMatch, the dollar sign and slice to control which elements of the array end up in
your result set.
And with that, you got full control over what you fetch with filtering
and then which fields of the found documents you include in your result set.