定义
$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 执行不等式检查,请使用以下语法:
{ price: { $not: { $eq: 1.99 } } }
上述查询等效于:
{ price: { $ne: 1.99 } }
以下 $not 查询无效,因为它尝试比较不使用操作符的字段:
{ price: { $not: 1.99 } }
行为
数组
当传递数组参数时,$not 操作符可能会产生意想不到的结果。要根据多个错误条件匹配文档,请使用 $nor。
正则表达式
$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