KeplerGrid guide

Classify MongoDB documents with $switch

Use $switch when each result needs a label based on several conditions. MongoDB evaluates the branches in order and uses the first one that matches.

Label orders by price

Load the practice orders, then open keplergrid_aggregation_stages.orders in KeplerGrid on a Read only connection. Select Aggregation → JSON, paste this pipeline, and choose Run pipeline.

[
  { "$sort": { "orderNo": 1 } },
  { "$set": {
    "priceLabel": { "$switch": {
      "branches": [
        { "case": { "$gte": ["$unitPrice", 100] }, "then": "Premium" },
        { "case": { "$gte": ["$unitPrice", 50] }, "then": "Standard" }
      ],
      "default": "Budget"
    } }
  } }
]

The branches test the higher price first. A numeric price below 50 reaches the fallback label. This fixture contains only numeric prices. If your price field can be absent or have a different BSON type, check the types before using the same rules on real data.

See which label each document received

In Stages, select $set. The Input and Output panels both show five orders. Output adds priceLabel to each result. Select Pipeline results to see the labels alongside the prices.

Expected labels for the practice prices
LabelPrices
Premium100.00
Standard50.00, 99.00
Budget15.00, 20.00

Swap the rules and compare the result

In the pipeline JSON, move the branch for 50 ahead of the branch for 100 and run again. The 100.00 order now becomes Standard, because it matches the earlier rule. Restore the original order to get Premium again. Keep default for documents that match neither rule.

The label exists only in these aggregation results. To count orders per label, group by priceLabel in a later stage.

For separate counts by numeric range, see the $bucket guide. For more calculated fields, see calculating values with $set.