$not

On this page本页内容

Definition定义

$not

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

$not performs a logical NOT operation on the specified <operator-expression> and selects the documents that do not match the <operator-expression>. 对指定的<operator expression>执行逻辑NOT操作,并选择与<operator-expression>不匹配的文档。This includes documents that do not contain the field.这包括不包含该字段的文档。

Consider the following query:考虑以下查询:

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

This query will select all documents in the inventory collection where:此查询将选择inventory集合中的所有文档,其中:

  • the price field value is less than or equal to 1.99 orprice字段值小于或等于1.99,或者
  • the price field does not existprice字段不存在

{ $not: { $gt: 1.99 } } is different from the $lte operator. $lte运算符不同。{ $lte: 1.99 } returns only the documents where price field exists and its value is less than or equal to 1.99.{$lte:1.99}仅返回存在price字段且其值小于或等于1.99的文档。

Remember that the $not operator only affects other operators and cannot check fields and documents independently. 请记住,$not运算符只影响其他运算符,不能单独检查字段和文档。So, use the $not operator for logical disjunctions and the $ne operator to test the contents of fields directly.因此,使用$not运算符进行逻辑析取,使用$ne运算符直接测试字段的内容。

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运算符的操作与其他运算符的行为一致,但对于某些数据类型(如数组)可能会产生意外的结果。

$not and Regular Expressions和正则表达式

$not operator can perform logical NOT operation on:运算符可以对以下各项执行逻辑NOT操作:

  • regular expression objects (i.e. /pattern/)正则表达式对象(即/pattern/

    For example, the following query selects all documents in the inventory collection where the item field value does notstart with the letter p.例如,以下查询选择inventory集合中item字段值不以字母p开头的所有文档。

    db.inventory.find( { item: { $not: /^p.*/ } } )
  • $regex operator expression (Starting in MongoDB 4.0.7)运算符表达式(从MongoDB 4.0.7开始)

    For example, the following query selects all documents in the inventory collection where the item field value does notstart with the letter p.例如,以下查询选择inventory集合中item字段值不以字母p开头的所有文档。

    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:例如,以下PyMongo查询使用Python的re.compile()方法编译正则表达式:

    import re
    for noMatch in db.inventory.find( { "item": { "$not": re.compile("^p.*") } } ):
        print noMatch
Tip提示
See also: 参阅:
←  $and$nor →