On this page
$not
$not
- 语法:
{ field: { $not: { <operator-expression> } } }
- 语法:
$not对指定的<operator-expression>
执行逻辑NOT
运算,并选择与<operator-expression>
不匹配的文档。这包括不包含field
的文档。
考虑以下查询:
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运算符的操作与其他运算符的行为一致,但对于某些数据类型(如数组)可能会产生意外结果。
考虑以下使用模式匹配表达式//
的示例:
db.inventory.find( { item: { $not: /^p.*/ } } )
该查询将选择inventory
集合中的所有文档,其中item
字段的值不是*以字母p
开头。
如果您使用的是 Python,则可以使用 PyMongo 驱动程序和 Python 的python:re.compile()
方法编写上述查询,以编译正则表达式,如下所示:
import re
for noMatch in db.inventory.find( { "item": { "$not": re.compile("^p.*") } } ):
print noMatch