$not

  • $not
  • Syntax: { field: { $not: { <operator-expression> } } }

$not performs a logical NOT operation on thespecified <operator-expression> and selects the documents thatdo not match the <operator-expression>. This includesdocuments that do not contain the field.

Consider the following query:

  1. db.inventory.find( { price: { $not: { $gt: 1.99 } } } )

This query will select all documents in the inventory collection where:

  • the price field value is less than or equal to 1.99 or
  • the price field does not exist{ $not: { $gt: 1.99 } } is different from the $lteoperator. { $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 otheroperators 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.

Behavior

$not and Data Types

The operation of the $not operator is consistent with thebehavior of other operators but may yield unexpected results with somedata 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 theinventory collection where the item field value does _not_start with the letter p.

  1. db.inventory.find( { item: { $not: /^p.*/ } } )
  • $regex operator expression (Starting in MongoDB 4.0.7)

For example, the following query selects all documents in theinventory collection where the item field value does _not_start with the letter p.

  1. db.inventory.find( { item: { $not: { $regex: "^p.*" } } } )
  2. db.inventory.find( { item: { $not: { $regex: /^p.*/ } } } )
  • driver language’s regular expression objects

For example, the following PyMongo query uses Python’sre.compile() method to compile a regularexpression:

  1. import re
  2. for noMatch in db.inventory.find( { "item": { "$not": re.compile("^p.*") } } ):
  3. print noMatch

See also

find(), update(), $set, $gt,$regex, PyMongo,driver.