Now let's do a different query,
we still have that text index on the description and let's search for awesome T-shirt. If we do this,
I find both entries because I have awesome here too in the first product.
Now finding both might be fine but you typically would want to order this differently,
for us humans it's pretty clear that the second product is the better hit because there we have both awesome
and t-shirt so would be nice if that would come first in our result list and we can actually get there
because mongodb does something interesting or special when managing such a text index or when searching
for text in a text index, we can find out how it scores its results and let's first of all find out with
the help of projection.
So here I'll add a second argument to my find method to project the results and I will simply output
a score field here
where I can use a special meta operator to add text score. This is a meta field added or managed by mongodb
for text searches
here with the $text
operator on a text index.
If I do this, you see the score.
mongodb assigned to a result
and here, it even automatically sort it by that score now as you can tell.
So here we see that the score is much higher for T-shirt and awesome than for just awesome and it automatically
sort it for us here
but if we want to make sure, we can of course also add sort here and we can then sort by score where
score is a document with $meta and then textScore written like this as a text and I should add
a dot in front of pretty. And now, it's definitely sorted,
it was before but now we enforce sorting by looking at that meta text score which mongodb manages
for us.
So this is simply a construct you can remember for when working with text and text indexes,
you can extract this meta information text score and both these words have to be written like this from
mongodb so to say, it manages that for us and we can see how it scores the results
and as you can see, we can then use that to order too.