文章目录
- 语法
- 使用
- 举例
$not聚合运算符用于将指定布尔表达式的值取反,比如,表达式的值为
true,
$not返回
false;表达式的值为
false,
$not则返回
true。
语法
{ $not: [ <expression> ] }
使用
除false外,null、0和undefined都被认为是false,其他值包括非零值和数组都被认为是true,如:
| 例子 | 结果 |
|---|---|
{ $not: [ true ] } | false |
{ $not: [ [ false ] ] } | false |
{ $not: [ false ] } | true |
{ $not: [ null ] } | true |
{ $not: [ 0 ] } | true |
举例
inventory集合有下列文档:
{ "_id" : 1, "item" : "abc1", "description": "product 1", "qty": 300 }
{ "_id" : 2, "item" : "abc2", "description": "product 2", "qty": 200 }
{ "_id" : 3, "item" : "xyz1", "description": "product 3", "qty": 250 }
{ "_id" : 4, "item" : "VWZ1", "description": "product 4", "qty": 300 }
{ "_id" : 5, "item" : "VWZ2", "description": "product 5", "qty": 180 }
下面的聚合操作使用$not运算符来判断qty是否不大于(小于等于)250:
db.inventory.aggregate([{$project:{item: 1,result: { $not: [ { $gt: [ "$qty", 250 ] } ] }}}]
)
操作返回下面的结果:
{ "_id" : 1, "item" : "abc1", "result" : false }
{ "_id" : 2, "item" : "abc2", "result" : true }
{ "_id" : 3, "item" : "xyz1", "result" : true }
{ "_id" : 4, "item" : "VWZ1", "result" : false }
{ "_id" : 5, "item" : "VWZ2", "result" : true }