$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行为

$or uses short-circuit logic: the operation stops evaluation after encountering the first true expression.$or使用短路逻辑:操作在遇到第一个真表达式后停止计算。

In addition to the false boolean value, $or evaluates as false the following: null, 0, and undefined values. 除了false布尔值,$or的计算结果为false,还包括以下值:null0undefined的值。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

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 }