11. Conditional Logic with $cond, $switch, and $ifNull

Aggregation expressions support business logic. $cond selects between two expressions based on a condition. $switch handles multiple branches and can provide a default. $ifNull supplies a fallback for null or missing values.

For example, classify orders into value bands based on their subtotal. The thresholds are application-specific business rules and should be documented and configured consistently.

Code Example
db.orders.aggregate([
  {
    $set: {
      subtotal: {
        $reduce: {
          input: { $ifNull: ["$items", []] },
          initialValue: 0,
          in: { $add: ["$$value", { $multiply: ["$$this.quantity", "$$this.price"] }] }
        }
      }
    }
  },
  {
    $set: {
      valueBand: {
        $switch: {
          branches: [
            { case: { $gte: ["$subtotal", 20000] }, then: "premium" },
            { case: { $gte: ["$subtotal", 10000] }, then: "high-value" },
            { case: { $gte: ["$subtotal", 3000] }, then: "standard" }
          ],
          default: "small"
        }
      }
    }
  }
]);
Key Takeaways
  • $cond handles two-way decisions.
  • $switch handles multiple branches.
  • $ifNull handles missing and null values.
  • Business thresholds should be explicit.
Knowledge Check

Which expression is suited to classifying values into several ranges?