定义
$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.99price字段值为非数字price字段不存在
{ $not: { $gt: 1.99 } } 与$lte 操作符不同。{ $lte: 1.99 } 仅返回 price字段存在且其值小于或等于1.99 的文档。
将 $not操作符与另一个操作符表达式一起使用。要使用 $not 进行不等式检查,请使用:
{ price: { $not: { $eq: 1.99 } } }
上述查询等效于:
{ price: { $ne: 1.99 } }
以下查询无效,因为它比较字段时没有操作符:
{ 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