$not
On this page
Definition
$not-
Syntax:
{ field: { $not: { <operator-expression> } } }$notperforms a logicalNOToperation on the specified<operator-expression>and selects the documents that do not match the<operator-expression>. This includes documents that do not contain thefield.Consider the following query:
db.inventory.find( { price: { $not: { $gt: 1.99 } } } )
This query will select all documents in the
inventorycollection where:-
the
pricefield value is less than or equal to1.99or -
the
pricefield does not exist
{ $not: { $gt: 1.99 } }is different from the$lteoperator.{ $lte: 1.99 }returns only the documents wherepricefield exists and its value is less than or equal to1.99.Remember that the
$notoperator only affects other operators and cannot check fields and documents independently. So, use the$notoperator for logical disjunctions and the$neoperator to test the contents of fields directly. -
Behavior
$not and Data Types
The operation of the $not operator is consistent with the behavior of other operators but may yield unexpected results with some data types like arrays.
$not and Regular Expressions
$not operator can perform logical NOT operation on:
-
Regular expression objects (i.e.
/pattern/)For example, the following query selects all documents in the
inventorycollection where theitemfield value does not start with the letterp.db.inventory.find( { item: { $not: /^p.*/ } } )
-
$regexoperator expressionFor example, the following query selects all documents in the
inventorycollection where theitemfield value does not start with the letterp.db.inventory.find( { item: { $not: { $regex: "^p.*" } } } ) db.inventory.find( { item: { $not: { $regex: /^p.*/ } } } )
-
driver language's regular expression objects
For example, the following PyMongo query uses Python's
re.compile()method to compile a regular expression:import re for noMatch in db.inventory.find( { "item": { "$not": re.compile("^p.*") } } ): print noMatch