MongoDB NOT operator ( $not )

MongoDB provides different types of logical query operators and $not operator is one of them. This operator is used to perform logical NOT operation on the specified operator expressions and select or retrieve only those documents that do not match the given operator expression. It also includes those documents that don’t contain the field. You can use this operator in methods like find(), update(), etc. according to your requirements.

  • Always use the $not operator with other operators because it cannot check the fields and documents independently and only affects other operators.
  • You can use the $not operator with regular expressions.
  • This operation of this operator is consistent with the behavior of other operators, but it may give some unexpected results with some data types like arrays.

Syntax:

{ field: { $not: { operator-expression } } }

In the following examples, we are working with:

Database: GeeksforGeeks
Collection: contributor
Document: three documents that contain the details of the contributors in the form of field-value pairs.



Matching values using $not operator:

In this example, we are retrieving only those employee’s documents whose salary is not greater than 2000.

filter_none

edit
close

play_arrow

link
brightness_4
code

db.contributor.find({salary: {$not: {$gt: 2000}}}).pretty()

chevron_right


Matching values in nested/embedded documents using $not operator:

In this example, we are retrieving only those employee’s documents whose age is not equal to 24.

filter_none

edit
close

play_arrow

link
brightness_4
code

db.contributor.find({"personal.age": {$not: {$eq: 24}}}).pretty()

chevron_right


Matching values in an array using $not operator:

In this example, we are retrieving only those employee’s documents that does not match the given array.

filter_none

edit
close

play_arrow

link
brightness_4
code

db.contributor.find({language: {$not: {$in: ["Java", "Perl"]}}}).pretty()

chevron_right





My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.