文档菜单
文档首页
/
MongoDB 手册
/ / /

$or (聚合)

在本页

  • 定义
  • 行为
  • 错误处理
  • 示例
$or

评估一个或多个表达式,如果其中任何表达式为真,则返回true。否则,$or返回false

$or有以下语法

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

有关表达式的更多信息,请参阅表达式运算符.

除了 false 布尔值之外,$or 还将以下值评估为 falsenull0undefined。对于其他所有值,包括非零数值和数组,$or 将其评估为 true

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

为了允许查询引擎优化查询,$or 以以下方式处理错误:

  • 如果提供给 $or 的任何表达式在单独评估时会导致错误,则包含该表达式的 $or 可能会导致错误,但错误不是保证发生的。

  • 提供给 $or 的第一个表达式之后的表达式即使第一个表达式评估为 true 也可能引发错误。

例如,以下查询在 $x0始终 产生错误。

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

以下包含多个提供给 $or 的表达式的查询,如果存在任何文档中 $x0,则 可能 产生错误。

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 }

返回

$objectToArray