In “M001, Chapter 4, Lecture: Query Operators - Logic” I have found a subtle error which was quite annoying for me, that’s why I share it here.
I emphasize that M001 is really a great course and all my gratitude to Yulia :), this is just a point which I think worth to mention.
At 4:15 Yulia says that “If we don’t specify an explicit $and
like this and just list one $or
after another, we’ll get documents that match either of the two $or
queries.”
{$or: [{src_airport: "KZN"}, {dst_airport: "KZN"}]}, {$or: [{airplane: "CR2"}, {airplane: "A81"}]}
This contains the error. In Atlas FILTER
button gets red, so it is clearly erroneous.
The problem is the following.
We can put an $and
query explicitly like {$and: [{X}, {Y}]}
and implicitly like {X, Y}
where X
and Y
are simple field: value
pairs.
But what Yulia does is {X}, {Y}
. Notice the difference in using the braces. Two expressions separated with a comma instead of one expression containing two conditions.
The correct impicit {X, Y}
-style query would be:
{$or: [{src_airport: "KZN"}, {dst_airport: "KZN"}], $or: [{airplane: "CR2"}, {airplane: "A81"}]}
Notice that this is one expression. The only difference from the flawed expression is the absence of two braces in the middle.
Yulia takes this wrong path of thinking further at 4:50: “So let’s add an explicit $and
in the beginning. I add the operator and the include the two $or
conditions in square brackets.” And she doesn’t bother the braces in any way! Yes, what she uses can be the inner part of an $and
's list but not a filter expression on its own.
Anyway, understandig what the problem is, improved my mongoDB skills.