$not¶
On this page
-
$not
¶ Syntax:
{ field: { $not: { <operator-expression> } } }
$not
performs a logicalNOT
operation 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:
This query will select all documents in the
inventory
collection where:- the
price
field value is less than or equal to1.99
or - the
price
field does not exist
{ $not: { $gt: 1.99 } }
is different from the$lte
operator.{ $lte: 1.99 }
returns only the documents whereprice
field exists and its value is less than or equal to1.99
.Remember that the
$not
operator only affects other operators and cannot check fields and documents independently. So, use the$not
operator for logical disjunctions and the$ne
operator to test the contents of fields directly.- the
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
inventory
collection where theitem
field value does not start with the letterp
.$regex
operator expression (Starting in MongoDB 4.0.7)For example, the following query selects all documents in the
inventory
collection where theitem
field value does not start with the letterp
.driver language’s regular expression objects
For example, the following PyMongo query uses Python’s
re.compile()
method to compile a regular expression: