mongodb3.6系列教程9--查询操作符之逻辑操作符

本文详细介绍了MongoDB中逻辑操作符$and、$not、$nor和$or的使用方法,包括语法、示例及索引操作等内容,帮助读者更好地理解和应用这些操作符。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 $and

1.1 语法

{ $and: [ { <expression1> }, { <expression2> } , ... , { <expressionN> } ] }

说明

  • $and操作符就是java中的&&,表示必须满足给定的所有条件。
  • $and操作符是短路操作,只要判断一个条件为false,后面都的都不会再计算。

1.2 示例

查询price字段等于1.99并且price字段存在的文档:

db.inventory.find( { $and: [ { price: { $ne: 1.99 } }, { price: { $exists: true } } ] } )

下面的写法等同于上面的写法:

db.inventory.find( { price: { $ne: 1.99, $exists: true } } )

备注: mongodb为每个逗号都提供了一个隐式的$and操作符,当单层逻辑的时候可以省略不写,但是多层逻辑嵌套的时候$and操作符不可省略。

嵌套逻辑操作符:
下面查询查询符合以下条件的文档:
1. price字段值等于0.99 or 1.99,并且
2. sale字段值等于true或者qty字段值小于20

db.inventory.find( {
    $and : [
        { $or : [ { price : 0.99 }, { price : 1.99 } ] },
        { $or : [ { sale : true }, { qty : { $lt : 20 } } ] }
    ]
} )

2 $not

2.1 语法

{ field: { $not: { <operator-expression> } } }

说明

  • $not操作符表示某个字段必须不满足给定的条件或者该字段不存在。

2.1 示例

查询price字段值不大于1.99或不存在price字段的文档

db.inventory.find( { price: { $not: { $gt: 1.99 } } } )

3 $nor

3.1 语法

{ $nor: [ { <expression1> }, { <expression2> }, ...  { <expressionN> } ] }

说明

  • $nor操作符的意思是给定的条件全部都不满足(包括字段不存在)

3.2 示例

查询price字段不存在或者price字段值不等于1.99 并且sale字段不存在或者sale字段值不等于true的文档

db.inventory.find( { $nor: [ { price: 1.99 }, { sale: true } ]  } )

4 $or

4.1 语法

{ $or: [ { <expression1> }, { <expression2> }, ... , { <expressionN> } ] }

说明

  • $or操作符的意思是给定的条件有一个满足即可
  • $or操作符可以嵌套

4.2 示例

查询quantity字段小于20或price字段等于10的文档

db.inventory.find( { $or: [ { quantity: { $lt: 20 } }, { price: 10 } ] } )

4.3 $or操作符索引操作

$or操作符如果要走索引,则每个条件的每个字段都得有索引才能走索引,例如:

db.inventory.find( { $or: [ { quantity: { $lt: 20 } }, { price: 10 } ] } )

上面的查询quantity字段和price字段都必须有索引才能走索引查询。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值