$match Restrictions?

Hi everyone,
I got the Lab: computing fields to work with $match and $project. I try to use only $match
I defined my pipeline as a variable and use it like: aggregate(pipeline)

var pipeline = [{$match: {$eq : [{$size : {$split :["$title"," "]}}, 1]}}]
this one works

but
var pipeline = [{$match: {{$size : {$split :["$title"," "]}} : 1}}]
doesn’t work.

Can someone explain me why?
Is it something related to “$match does not accept raw aggregation expressions” as mentioned in the documentation? I don’t really catch the phrase “raw aggregation expressions”. Could you explain it a bit? :smiley: Thank you.

Why are you trying to do this all in a $match stage?

My understanding is that the purpose of a $match stage is to test the values of fields which already exist against some condition. What your pipeline is trying to achieve is “give me the documents whose title field is a single word”, so you’re trying to test the length of the “number of words in the title” field to see whether or not it’s 1.

But the “number of words in the title” field doesn’t exist in your documents yet. That’s what a $project or $addFields stage can do, create the “number of words in the title” field by splitting the title into an array at each occurrence of a space and then counting the number of elements in the resulting array. The “number of words in the title” field is then available for a subsequent $match stage to use.

Of course, if you want a $match as the first stage in your pipeline, to filter out lots of documents that you know you’re not interested in based on fields that they already have, then you can do so, and then have a $project or $addFields stage to calculate things like “number of words in the title”, and then have another $match stage to filter the documents further based on the fields calculated in the $project or $addFields stage.

I am, of course, only a fellow student on this course, and am happy to be corrected by the experts :smiley:

2 Likes

@Simon_39939

No corrections; you nailed it. :wink: