$or (聚合)
定义
行为
除了 false
布尔值之外,$or
还将以下值评估为 false
:null
、0
和 undefined
。对于其他所有值,包括非零数值和数组,$or
将其评估为 true
。
示例 | 结果 |
---|---|
{ $or: [ true, false ] } | true |
{ $or: [ [ false ], false ] } | true |
{ $or: [ null, 0, undefined ] } | false |
{ $or: [ ] } | false |
错误处理
为了允许查询引擎优化查询,$or
以以下方式处理错误:
如果提供给
$or
的任何表达式在单独评估时会导致错误,则包含该表达式的$or
可能会导致错误,但错误不是保证发生的。提供给
$or
的第一个表达式之后的表达式即使第一个表达式评估为true
也可能引发错误。
例如,以下查询在 $x
为 0
时 始终 产生错误。
db.example.find( { $expr: { $eq: [ { $divide: [ 1, "$x" ] }, 3 ] } } )
以下包含多个提供给 $or
的表达式的查询,如果存在任何文档中 $x
为 0
,则 可能 产生错误。
db.example.find( { $or: [ { x: { $eq: 0 } }, { $expr: { $eq: [ { $divide: [ 1, "$x" ] }, 3 ] } } ] } )
示例
考虑以下文档的库存集合
{ "_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
运算符来确定是否数量
大于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 }