赞
踩
$or
聚合运算符计算一个或多个表达式的布尔值,只要其中一个表达式为true,则返回true,只有全部为false,才返回false。
{ $or: [ <expression1>, <expression2>, ... ] }
除false
外,null
、0
和undefined
都被认为是false
,其他值包括非零值和数组都被认为是true
,如:
例子 | 结果 |
---|---|
{ $or: [ true, false ] } | true |
{ $or: [ [ false ], false ] } | true |
{ $or: [ null, 0, undefined ] } | false |
{ $or: [ ] } | false |
为了让查询引擎优化查询,$or
按下面的方式处理错误:
$or
的任何表达式在单独计算时会导致错误,则包含该表达式的$or
可能会导致错误,但不保证一定会发生错误。true
,提供给$or
的其他表达式也可能会导致错误。例如,如果$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 ] } }
]
} )
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 }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。