对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

$not(查询谓词运算操作符)

$not

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

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

  • MongoDB Atlas:用于云中 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 }
    )
  • $regex 操作符表达式

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

    db.movies.find(
    { title: { $not: { $regex: "^T" } }, runtime: { $gt: 1000 } },
    { _id: 0, title: 1, runtime: 1 }
    )

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

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

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

    import re
    for noMatch in db.inventory.find( { "item": { "$not": re.compile("^p.*") } } ):
    print noMatch
给本页内容打分