$or (aggregation)

On this page本页内容

Definition定义

$or

Evaluates one or more expressions and returns true if any of the expressions are true. 计算一个或多个表达式,如果任何表达式为true,则返回trueOtherwise, $or returns false.否则,$or返回false

$or has the following syntax:语法如下:

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

For more information on expressions, see Expressions.有关表达式的详细信息,请参阅表达式

Behavior行为

In addition to the false boolean value, $or evaluates as false the following: null, 0, and undefined values. 除了false布尔值之外,$or还将以下值计算为falsenull0undefined的值。The $or evaluates all other values as true, including non-zero numeric values and arrays.$or将所有其他值计算为true,包括非零数值和数组。

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

Error Handling错误处理

To allow the query engine to optimize queries, $or handles errors as follows:要允许查询引擎优化查询,$or按如下方式处理错误:

  • If any expression supplied to $or would cause an error when evaluated alone, the $or containing the expression may cause an error but an error is not guaranteed.如果提供给$or的任何表达式在单独计算时会导致错误,则包含表达式的$or可能会导致错误但不保证会出现错误。
  • An expression supplied after the first expression supplied to $or may cause an error even if the first expression evaluates to true.在提供给$or的第一个表达式之后提供的表达式可能会导致错误,即使第一个表达式的计算结果为true

For example, the following query always produces an error if $x is 0:例如,如果$x为0,以下查询始终会产生错误:

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

The following query, which contains multiple expressions supplied to $or, may produce an error if there is any document where $x is 0:以下查询包含提供给$or的多个表达式,如果存在$x0的任何文档,则可能会产生错误:

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

Example示例

Consider an inventory collection with the following documents:考虑使用以下文档进行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 }

The following operation uses the $or operator to determine if qty is greater than 250 or less than 200:以下操作使用$or运算符确定qty是否大于250小于200

db.inventory.aggregate(
   [
     {
       $project:
          {
            item: 1,
            result: { $or: [ { $gt: [ "$qty", 250 ] }, { $lt: [ "$qty", 200 ] } ] }
          }
     }
   ]
)

The operation returns the following results:该操作返回以下结果:

{ "_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 }
←  $objectToArray (aggregation)$pow (aggregation) →