$or (aggregation)

Definition

  • $or
  • Evaluates one or more expressions and returns true if any ofthe expressions are true. Otherwise, $or returnsfalse.

$or has the following syntax:

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

For more information on expressions, seeExpressions.

Behavior

$or uses short-circuit logic: the operation stopsevaluation after encountering the first true expression.

In addition to the false boolean value, $or evaluatesas false the following: null, 0, and undefinedvalues. The $or evaluates all other values as true,including non-zero numeric values and arrays.

Example Result
{ $or: [ true, false ] } true
{ $or: [ [ false ], false ] } true
{ $or: [ null, 0, undefined ] } false
{ $or: [ ] } false

Example

Consider an inventory collection with the following documents:

  1. { "_id" : 1, "item" : "abc1", description: "product 1", qty: 300 }
  2. { "_id" : 2, "item" : "abc2", description: "product 2", qty: 200 }
  3. { "_id" : 3, "item" : "xyz1", description: "product 3", qty: 250 }
  4. { "_id" : 4, "item" : "VWZ1", description: "product 4", qty: 300 }
  5. { "_id" : 5, "item" : "VWZ2", description: "product 5", qty: 180 }

The following operation uses the $or operator todetermine if qty is greater than 250 or less than 200:

  1. db.inventory.aggregate(
  2. [
  3. {
  4. $project:
  5. {
  6. item: 1,
  7. result: { $or: [ { $gt: [ "$qty", 250 ] }, { $lt: [ "$qty", 200 ] } ] }
  8. }
  9. }
  10. ]
  11. )

The operation returns the following results:

  1. { "_id" : 1, "item" : "abc1", "result" : true }
  2. { "_id" : 2, "item" : "abc2", "result" : false }
  3. { "_id" : 3, "item" : "xyz1", "result" : false }
  4. { "_id" : 4, "item" : "VWZ1", "result" : true }
  5. { "_id" : 5, "item" : "VWZ2", "result" : true }