MongoDB聚合运算符:$not

文章目录

$not聚合运算符用于将指定布尔表达式的值取反,比如,表达式的值为 true$not返回 false;表达式的值为 false$not则返回 true

语法

js 复制代码
{ $not: [ <expression> ] }

使用

false外,null0undefined都被认为是false,其他值包括非零值和数组都被认为是true,如:

例子 结果
{ $not: [ true ] } false
{ $not: [ [ false ] ] } false
{ $not: [ false ] } true
{ $not: [ null ] } true
{ $not: [ 0 ] } true

举例

inventory集合有下列文档:

json 复制代码
{ "_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

js 复制代码
db.inventory.aggregate(
   [
     {
       $project:
          {
            item: 1,
            result: { $not: [ { $gt: [ "$qty", 250 ] } ] }
          }
     }
   ]
)

操作返回下面的结果:

json 复制代码
{ "_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 }
相关推荐
NineData3 小时前
数据库迁移总踩坑?用 NineData 迁移评估,提前识别所有兼容性风险
数据库·程序员·云计算
赵渝强老师5 小时前
【赵渝强老师】PostgreSQL中表的碎片
数据库·postgresql
全栈老石9 小时前
拆解低代码引擎核心:元数据驱动的"万能表"架构
数据库·低代码
倔强的石头_1 天前
kingbase备份与恢复实战(二)—— sys_dump库级逻辑备份与恢复(Windows详细步骤)
数据库
jiayou642 天前
KingbaseES 实战:深度解析数据库对象访问权限管理
数据库
李广坤3 天前
MySQL 大表字段变更实践(改名 + 改类型 + 改长度)
数据库
爱可生开源社区4 天前
2026 年,优秀的 DBA 需要具备哪些素质?
数据库·人工智能·dba
AI全栈实验室4 天前
MongoDB迁移金仓踩了5个坑,最后一个差点回滚
mongodb
随逸1774 天前
《从零搭建NestJS项目》
数据库·typescript
加号35 天前
windows系统下mysql多源数据库同步部署
数据库·windows·mysql