Docs 菜单
Docs 主页
/ /

$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.movies.find( { runtime: { $not: { $gt: 180 } } } )

该示例选择 movies 集合中满足如下条件的所有文档:

  • runtime 字段值小于或等于 180

  • runtime 字段不存在

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

必须将 $not 操作符与其他操作符表达式一起使用。例如,要使用 $not 执行不等式检查,请使用以下语法:

{ runtime: { $not: { $eq: 120 } } }

上述查询等效于:

{ runtime: { $ne: 120 } }

以下查询无效,因为它比较字段而未使用操作符:

{ runtime: { $not: 120 } }

当传递数组参数时,$not 操作符可能会产生意想不到的结果。要根据多个错误条件匹配文档,请使用 $nor

本页上的示例使用sample_mflix示例数据集中的数据。有关如何将此数据集加载到自管理MongoDB 部署中的详细信息,请参阅加载示例数据集。如果对示例数据库进行了任何修改,则可能需要删除并重新创建数据库才能运行本页上的示例。

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

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

    以下示例返回 runtime 大于 1000 分钟且 title 不是以字母 T 开头的电影。由于 $not 还匹配不包含 title字段的文档,因此即使标题数据不可用,该查询也会返回电影:

    db.movies.find(
    { title: { $not: /^T/ }, runtime: { $gt: 1000 } },
    { _id: 0, title: 1, runtime: 1 }
    )
    [
    { title: 'Centennial', runtime: 1256 },
    { title: 'Baseball', runtime: 1140 }
    ]
  • $regex 操作符表达式

    以下两个查询返回 runtime 大于 1000 分钟且 title 不是以字母 T 开头的电影。第一个查询将 string 传递给 $regex

    db.movies.find(
    { title: { $not: { $regex: "^T" } }, runtime: { $gt: 1000 } },
    { _id: 0, title: 1, runtime: 1 }
    )
    [
    { title: 'Centennial', runtime: 1256 },
    { title: 'Baseball', runtime: 1140 }
    ]

    第二个查询将正则表达式字面量传递给 $regex

    db.movies.find(
    { title: { $not: { $regex: /^T/ } }, runtime: { $gt: 1000 } },
    { _id: 0, title: 1, runtime: 1 }
    )
    [
    { title: 'Centennial', runtime: 1256 },
    { title: 'Baseball', runtime: 1140 }
    ]
  • 驱动程序语言的正则表达式对象

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

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

提示

后退

$nor

在此页面上