Docs 菜单

Docs 主页开发应用程序MongoDB Manual

$not

在此页面上

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

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

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

  • MongoDB Atlas :用于在云中部署 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 →