M121: Lab using $lookups

What is the difference between
$match: {xyz: /123 | 455/}
and
$match: {xyz: {$in: ["123","455"]}}

Basically why does the former give a different result than the latter one?

Hi Apurva,

The first example uses a regular expression (https://docs.mongodb.com/master/reference/operator/query/regex/#op._S_regex) to pattern match for specific strings whilst the second uses the $in operator to match any documents with the field ‘xyz’ whose value are exactly the same as any element of the array given (so either “123” or “455” in this case).

The different result for the regular expression is that “/123 | 455/”, specifically "123 " will match “123whitespacecharacter” rather than “123”. Additionally, “/123” is unanchored so it will match the character sequence “123” in any part of the xyx field in any document. For example the document { xyz: “777123” } would be matched. For best performance with regular expressions in MongoDB it’s often best to anchor the expression (https://docs.mongodb.com/master/reference/operator/query/regex/index.html#index-use) using a caret ( ^ ) or a left anchor ( \A ). In the example above, this would mean that it would find any document with the field ‘xyz’ that started with “123” so it would match “123” but also “1234”.

Hope this helps explain the difference.
Eoin

1 Like

So will this expression /^123$ | ^455$/match documents containing the field xyz with a value of 123 and 455 only. Will this remove the other kinds?

Thanks.
Apurva

Hi @Apurva_Kunkulol

That’s correct, it will match for documents with the field xyz which only contain the exact values of 123 or 455. It will not match any other values.

Hope this helps!
Eoin

1 Like