M121: General Question on $match usage

field1, field2, field3 are of type array

{
        $match: {
            field1 : { $elemMatch: { $in : field2, $in: field3 } }
        }

    }

However this code gives me [js] ReferenceError: field2 is not defined :
Why so and whats the right syntax?

{
        $match: {
            field1 : { $elemMatch: { $in : "$field2", $in: "$field3" } }
        }

    }

However this code gives me “errmsg” : "$in needs an array"
Why so and whats the right syntax?

Hey @Ankur_Agarwal_44076

So there are 2 different versions of $in. One is the query operator version and the other is the aggregation version. FYI I had this very same issue while going through the course.

You will see that the aggregation version can take expression or array expression for values

{ $in: [ <expression>, <array expression> ] }

However, the $in which is used in the $match stage is the query operator version which takes an array of values. As,

$match takes a document that specifies the query conditions. The query syntax is identical to the read operation query syntax; i.e. $match does not accept raw aggregation expressions.

{ field: { $in: [<value1>, <value2>, ... <valueN> ] } }

To accomplish your task you may want to look through the Aggregation Pipeline Operators list for what you will need.