$or

The `$or` operator performs a logical OR operation on an array of expressions and retrieves documents that satisfy at least one of the specified conditions.

Syntax

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

Parameters

expressionobjectrequired

An array of expressions, where at least one must be true for a document to be included

Examples

Find stores matching any condition

This query retrieves stores with more than 15 full-time staff or more than 20 part-time staff using the $or operator.

Query:

db.stores.find(
  {
    $or: [
      { "staff.employeeCount.fullTime": { $gt: 15 } },
      { "staff.employeeCount.partTime": { $gt: 20 } }
    ]
  },
  { "name": 1, "staff": 1 }
).limit(2)

Output:

[
  { "_id": "dda2a7d2-6984-40cc-bbea-4cbfbc06d8a3", "name": "Contoso, Ltd. | Home Improvement Closet - Jaskolskiview", "staff": { "employeeCount": { "fullTime": 16, "partTime": 8 } } },
  { "_id": "44fdb9b9-df83-4492-8f71-b6ef648aa312", "name": "Fourth Coffee | Storage Solution Gallery - Port Camilla", "staff": { "employeeCount": { "fullTime": 17, "partTime": 15 } } }
]

Evaluate alternative conditions

This query retrieves stores that have either total sales greater than 50,000 or more than 25 total staff members.

Query:

db.stores.aggregate([
  {
    $project: {
      name: 1,
      totalSales: "$sales.totalSales",
      totalStaff: { $add: ["$staff.employeeCount.fullTime", "$staff.employeeCount.partTime"] },
      qualifiesForProgram: {
        $or: [
          { $gt: ["$sales.totalSales", 50000] },
          { $gt: [{ $add: ["$staff.employeeCount.fullTime", "$staff.employeeCount.partTime"] }, 25] }
        ]
      }
    }
  },
  { $limit: 4 }
])

Output:

[
  { "_id": "905d1939-e03a-413e-a9c4-221f74055aac", "name": "Trey Research | Home Office Depot - Lake Freeda", "totalStaff": 31, "qualifiesForProgram": true },
  { "_id": "a715ab0f-4c6e-4e9d-a812-f2fab11ce0b6", "name": "Lakeshore Retail | Holiday Supply Hub - Marvinfort", "totalStaff": 27, "qualifiesForProgram": true }
]

Related