当前位置:   article > 正文

MongoDB聚合运算符:$or_mongodb $or

mongodb $or


$or聚合运算符计算一个或多个表达式的布尔值,只要其中一个表达式为true,则返回true,只有全部为false,才返回false。

语法

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

  • 1
  • 2

使用

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

例子结果
{ $or: [ true, false ] }true
{ $or: [ [ false ], false ] }true
{ $or: [ null, 0, undefined ] }false
{ $or: [ ] }false

错误处理

为了让查询引擎优化查询,$or按下面的方式处理错误:

  • 如果提供给$or的任何表达式在单独计算时会导致错误,则包含该表达式的$or可能会导致错误,但不保证一定会发生错误。
  • 即使第一个表达式的计算结果为true,提供给$or的其他表达式也可能会导致错误。

例如,如果$x0,以下查询始终会产生错误:

db.example.find( {
   $expr: { $eq: [ { $divide: [ 1, "$x" ] }, 3 ] }
} )
  • 1
  • 2
  • 3

以下查询包含提供给$or的多个表达式,如果存在$x0的任何文档,则可能会产生错误:

db.example.find( {
   $or: [
      { x: { $eq: 0 } },
      { $expr: { $eq: [ { $divide: [ 1, "$x" ] }, 3 ] } }
   ]
} )
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

举例

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 }
  • 1
  • 2
  • 3
  • 4
  • 5

下面的聚合操作使用$or运算符来判断qty是否大于250或小于200

db.inventory.aggregate(
   [
     {
       $project:
          {
            item: 1,
            result: { $or: [ { $gt: [ "$qty", 250 ] }, { $lt: [ "$qty", 200 ] } ] }
          }
     }
   ]
)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

操作返回下面的结果:

{ "_id" : 1, "item" : "abc1", "result" : true }
{ "_id" : 2, "item" : "abc2", "result" : false }
{ "_id" : 3, "item" : "xyz1", "result" : false }
{ "_id" : 4, "item" : "VWZ1", "result" : true }
{ "_id" : 5, "item" : "VWZ2", "result" : true }
  • 1
  • 2
  • 3
  • 4
  • 5
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/655295
推荐阅读
相关标签
  

闽ICP备14008679号