On this page
$or (aggregation)
在本页面
Definition
$or
- 计算一个或多个表达式,如果**中的任何一个为
true
,则返回true
。否则,$or返回false
。
- 计算一个或多个表达式,如果**中的任何一个为
$or具有以下语法:
{ $or: [ <expression1>, <expression2>, ... ] }
有关表达式的更多信息,请参见Expressions。
Behavior
$or使用短路逻辑:遇到第一个true
表达式后,该操作停止求值。
除了false
布尔值外,$or还将以下值评估为false
:null
,0
和undefined
值。 $or会将所有其他值评估为true
,包括非零数值和数组。
Example | Result | |
---|---|---|
{ $or: [ true, false ] } |
true |
|
{ $or: [ [ false ], false ] } |
true |
|
{ $or: [ null, 0, undefined ] } |
false |
|
{ $or: [ ] } |
false |
Example
考虑包含以下文档的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 }
以下操作使用$or运算符确定qty
是大于 250 *还是小于200
:
db.inventory.aggregate(
[
{
$project:
{
item: 1,
result: { $or: [ { $gt: [ "$qty", 250 ] }, { $lt: [ "$qty", 200 ] } ] }
}
}
]
)
该操作返回以下结果:
{ "_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 }