“文档” 菜单
文档首页
/
MongoDB Manual
/ / / /

$not

在此页面上

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

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

可以使用 $not 查找托管在以下环境中的部署:

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

  • MongoDB Enterprise:基于订阅、自我管理的 MongoDB 版本

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

$not 操作符采用以下形式:

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

考虑以下示例:

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

该查询选择 inventory 集合中满足如下条件的所有文档:

  • price 字段值小于或等于 1.99

  • price 字段不存在

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

请记住, $not操作符仅影响其他操作符,而不能独立检查字段和文档。因此,使用$not操作符进行逻辑或,并使用$ne操作符直接测试字段的内容。

$not操作符的操作与其他操作符的行为一致,但对于某些数据类型(如数组)可能会产生意外结果。

$not 操作符可以对以下情况执行逻辑 NOT 操作:

  • 正则表达式对象(即 /pattern/

    例如,以下查询选择 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.*/ } } } )
  • 驱动程序语言的正则表达式对象

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

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

提示

另请参阅:

← $and
$nor →