$not operator VS $ne operator

Suppose that we want to find the people’s age that is not equal to 18.
Which one is correct and why?

Option A. { “$not” : [ { “age” : 18 } ] }

Option B. { “age” : { “$ne” : 18 } }

In Chapter 4, Quiz 2-Logic Operator, Problem is -

Problem:

Which is the most succinct query to return all documents from the sample_training.inspections collection where the inspection date is either “Feb 20 2015”, or “Feb 21 2015” and the company is not part of the “Cigarette Retail Dealer - 127” sector?

Answer :

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

is true, but

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

as false,
why?

Hi @Thwin_Htet_Win,

Welcome to the MongoDB Community Forums,

The $not operator is used for logical disjunctions i.e., it only affects other operators means used to perform logical NOT operation on other operators and cannot check fields and documents independently, whereas the $ne operator is used to test the contents of fields directly.

For more info on $not read here

So, here :point_down:

"$not" will not act on key-value independently, as stated above, it just used to perform logical NOT operation on other operators, so Option A is incorrect, and likely Option B is correct as "$ne" is directly performing the operation on the value of the key because it is meant to be. Read here for more information.

The same is applicable for this one also :point_down:

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

is true, but

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

as false,
why?

Hope it helps,

Thanks,
Kushagra

1 Like

Thanks for your detailed answer.It helps me a lot.
Taking a note with real strong understanding makes me feel motivated.
If u don’t mind, i suggest you to add $ne VS $not explanation on lecture please. (for people like me.)

Hi @Thwin_Htet_Win,

Thanks for your appreciation.
We will surely consider your suggestion.

Regards,
Kushagra

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