文档菜单
文档首页
/
MongoDB 手册
/ / / /

$not

在本页

  • 定义
  • 兼容性
  • 语法
  • 行为
$not

$not 对指定的 <operator-expression> 执行逻辑 NOT 操作,并选择与 <operator-expression> 不匹配的文档。这包括不包含 字段 的文档。

您可以使用 $not 在以下环境中部署

  • MongoDB Atlas:云中 MongoDB 部署的完全托管服务

  • MongoDB Enterprise:基于订阅的自托管 MongoDB 版本

  • MongoDB Community:源代码可用的、免费使用且可自托管的 MongoDB 版本

操作符 $not 的形式如下

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

考虑以下查询示例

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

此查询选择所有满足以下条件之一的 inventory 集合中的文档

  • 价格字段值小于或等于 1.99

  • 价格字段值不是数字

  • 价格字段不存在

{ $not: { $gt: 1.99 } }$lte 操作符不同。 { $lte: 1.99 } 仅返回存在价格字段且其值小于或等于 1.99 的文档。

您必须使用 $not 操作符与另一个操作符表达式一起使用。例如,要使用 $not 进行不等式检查,请使用此语法

{ price: { $not: { $eq: 1.99 } } }

前面的查询等价于

{ price: { $ne: 1.99 } }

以下 $not 查询是 无效的,因为它尝试比较没有操作符的字段

{ price: { $not: 1.99 } }

当传入数组参数时,$not运算符可能会产生意外的结果。为了匹配基于多个错误条件的结果,请使用$nor

$not运算符可以对

  • 正则表达式对象(即/模式/)执行逻辑NOT操作

    例如,以下查询选择所有在inventory集合中,item字段值不以字母p开头的文档。

    db.inventory.find( { item: { $not: /^p.*/ } } )
  • $regex运算符表达式

    例如,以下查询选择所有在inventory集合中,item字段值不以字母p开头的文档。

    db.inventory.find( { item: { $not: { $regex: "^p.*" } } } )
    db.inventory.find( { item: { $not: { $regex: /^p.*/ } } } )
  • 驱动语言的正则表达式对象

    例如,以下查询使用Python的re.compile()方法编译正则表达式

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

提示

另请参阅

返回

$and