Wrong Explanation for Chapter 4 Quiz 2: Logic Operators

The question asks for the most succinct query that satisfies a condition, and the correct answer is

    db.inspections.find(
    { "$or": [ { "date": "Feb 20 2015" },
                { "date": "Feb 21 2015" } ],
        "sector": { "$ne": "Cigarette Retail Dealer - 127" }}).pretty()

A query whose complexity seems similar but that does not work is

   { "$or": [ { "date": "Feb 20 2015" },
               { "date": "Feb 21 2015" }],
       "$not": { "sector": "Cigarette Retail Dealer - 127" }}).pretty()

The explanation is

While this query looks for the right dates and correctly uses the $or operator, it is incorrectly using the $not logic operator. $not negates a logical expression, and in this case, will result in an error.

However, would this not be a logical expression from an implicit $eq?

    { "$or": [ { "date": "Feb 20 2015" },
                { "date": "Feb 21 2015" }],
        "$not": { "sector": "Cigarette Retail Dealer - 127" }}).pretty()

When I read the MongoDB documentation, the real reason why it fails is that $not must be applied to a field, and cannot be top-level like $and and $or.
{ field: { $not: { <operator-expression> } } }

1 Like

The code blocks didn’t format correctly, and I can’t edit the original post. Also, the third code block should be

db.inspections.find(
{ "$or": [ { "date": "Feb 20 2015" },
            { "date": "Feb 21 2015" }],
    "$not": { "sector": { "$eq": "Cigarette Retail Dealer - 127" } }}).pretty()

Hi @victorz, welcome to the community.
Please note that the correct syntax for $not operator is as below:
{ field: { $not: { <operator-expression> } } }

therefore the following query is invalid:

I hope it helps.

In case you have any doubts, please feel free to reach out to us.

Thanks and Regards.
Sourabh Bagrecha,
Curriculum Services Engineer

As I’ve noted in my original post, $not requires the format { field: { $not: { <operator-expression> } } }, which is the true reason why the query is invalid.

However, in the lecture video and solution explanation, they do not explain this correctly, which is why I posted this thread.

2 Likes

Understood, thank you so much for pointing this out, I have escalated this issue to the appropriate channel. Please be rest assured that our team is working on it and we will try our best to fix it as soon as possible.
Meanwhile, if you have any doubts please feel free to reach out to us and we will be more than happy to help you.

Thanks. Regards.
Sourabh Bagrecha,
Curriculum Services Engineer.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.