Definition
$orEvaluates one or more expressions and returns
trueif any of the expressions aretrue. Otherwise,$orreturnsfalse.$orhas the following syntax:{ $or: [ <expression1>, <expression2>, ... ] } For more information on expressions, see Expressions.
Behavior
In addition to the false boolean value, $or evaluates
as false the following: null, 0, and undefined
values. The $or evaluates all other values as true,
including non-zero numeric values and arrays.
Example | Result |
|---|---|
|
|
|
|
|
|
|
|
Error Handling
To allow the query engine to optimize queries, $or handles
errors as follows:
If any expression supplied to
$orwould cause an error when evaluated alone, the$orcontaining the expression may cause an error but an error is not guaranteed.An expression supplied after the first expression supplied to
$ormay cause an error even if the first expression evaluates totrue.
For example, the following query always produces an error if $x is
0:
db.example.find( { $expr: { $eq: [ { $divide: [ 1, "$x" ] }, 3 ] } } )
The following query, which contains multiple expressions supplied to
$or, may produce an error if there is any document where $x
is 0:
db.example.find( { $or: [ { x: { $eq: 0 } }, { $expr: { $eq: [ { $divide: [ 1, "$x" ] }, 3 ] } } ] } )
Example
Consider an inventory collection with the following documents:
{ "_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:
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 }